Reputation: 1086
I want to detect a change in the input value where the change was made by JS.
HTML:
<input type="text" name="test_input"><br><br>
<button name="change_input">Change usign JS </button>
JS:
$(function() {
$('body').on('change','input[name="test_input"]',function() {
alert('Changed');
});
$('button[name="change_input"]').on('click',function() {
$('input[name="test_input"]').val('New value');
});
})
https://jsfiddle.net/7c54r7x9/
Thanks
Upvotes: 2
Views: 6077
Reputation: 1955
Change your code as below. Hope this will help you
$(function() {
$('input[name="test_input"]').change(function() {
alert('Changed');
});
$('button[name="change_input"]').on('click',function() {
$('input[name="test_input"]').val('New value');
$('input[name="test_input"]').trigger("change");
});
})
Upvotes: 0
Reputation: 337560
The change event is only raised when the modification is made by user input. When it's set programmatically you'll need to raise the event yourself. In jQuery, you can do that by using trigger()
, like this:
$(function() {
$('body').on('change', 'input[name="test_input"]', function() {
console.log('Changed');
});
$('button[name="change_input"]').on('click', function() {
$('input[name="test_input"]').val('New value').trigger('change');
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="test_input"><br><br>
<button name="change_input">Change usign JS </button>
Upvotes: 6