stack stack - 5 months ago 15
jQuery Question

Is there any event to detect the value of textarea changes?

I have this code:



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

$("#bold").on('click', function(e){ $("#textarea_id").val('bold'); });
$("#italic").on('click', function(e){ $("#textarea_id").val('italic'); });
$("#underline").on('click', function(e){ $("#textarea_id").val('underline'); });
$("#center").on('click', function(e){ $("#textarea_id").val('center'); });
$("#leftside").on('click', function(e){ $("#textarea_id").val('leftside'); });

<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>
<button id = "italic">I</button>
<button id = "underline">U</button>
<button id = "center">C</button>
<button id = "leftside">L</button>





Currently I'm using
input
event to detect the value of that textarea changes. But as you see it doesn't work. I mean when I click on each of those buttons, I don't see this alert
'the value of textarea changed'
.

I can do that by adding
.change()
in the end of these:

$("#textarea_id").val('bold').change();
$("#textarea_id").val('bold').change();
.
.
.


But this ^ isn't what I'm looking for. I need an event based on the changes on the textarea. So I want an event for here:

$("#textarea_id").on(' /* event here */ ', function(e){


Is there any event to be sensitive than changing the value of textarea by
.val()
?

Answer

Here's my solution:

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

	$(".myButton").click(function(){
		var elementValue = $(this).attr("id");
		$("#textarea_id").val(elementValue).trigger("change");
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<textarea id="textarea_id"></textarea>
<br>
<button class = "myButton"     id="bold">B</button>
<button class = "myButton"     id="italic">I</button>
<button class = "myButton"     id="underline">U</button>
<button class = "myButton"     id="center">C</button>
<button class = "myButton"     id="leftside">L</button>

Comments