Shafizadeh
Shafizadeh

Reputation: 10340

Is there any event executed when the value of textarea changes?

Here is a simplified snippet of my code:

$("#textarea_id").on('input propertychange', function(e){
	alert('the value of textarea changed');
});

$("#bold").on('click', function(e){
	$("#textarea_id").val('bold');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id = "textarea_id"></textarea>
<br>
<button id = "bold">
B
</button>

I want to see that alert when the value of that textarea changes (in any way). As you see it just runs when we write something into that textarea, but not when we click on that button (while it should be, because when we click on that button, the value of that textarea changes). How can I make it sensitive for every kind of changes?

Upvotes: 0

Views: 52

Answers (1)

Satpal
Satpal

Reputation: 133403

You can use change event. However programmatically changing value will not automatically trigger the event handler.

To trigger the event handler, trigger(event) can be used.

Execute all handlers and behaviors attached to the matched elements for the given event type.

Also note: .change() is just shorthand for .trigger('change')

$("#textarea_id").on('input change', function(e){
	alert('the value of textarea changed');
});

$("#bold").on('click', function(e){
	$("#textarea_id").val('bold').trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id = "textarea_id"></textarea>
<br>
<button id = "bold">
B
</button>

Upvotes: 2

Related Questions