How to fire JQuery change event when input value changed programmatically?
Solution 1:
change event only fires when the user types into the input and then loses focus.
You need to trigger the event manually using change()
or trigger('change')
$("input").change(function() {
console.log("Input text changed!");
});
$("input").val("A").change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' />
Solution 2:
The event handler .change()
behaves like a form submission - basically when the value changes on submit the console will log. In order to behave on text input you would want to use input, like below:
$("input").on('input', function(){
console.log("Input text changed!");
});
$("input").val("A");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' />
Solution 3:
What you need to do is trigger the change
event after you've set the text. So you may create a function to do that so you won't have to repeat it every time you need to update the text, like this:
function changeTextProgrammatically(value) {
$("input").val( value );
$("input").trigger( 'change' ); // Triggers the change event
}
changeTextProgrammatically( "A" );
I've updated the fiddle,