0

HTML

<input id="testinput" type="text"></input>  

JS

$('#testinput').change(function (){
    change();
});
function change(){
    alert();
}
$('#testinput').val('new val');  

Link
By typing in input and losing focus it works, but if a change of the input field is triggered by jquery, it does not work.
$('#testinput').val('new val').trigger('change'); not required.

ozil
  • 6,930
  • 9
  • 33
  • 56
  • $(elem).val('text') doesn't trigger a change. See this post: http://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquer – binderbound May 21 '15 at 08:04
  • If you change teh value programatically the change event won't be triggered, So I guess you no choice but to use `tigger` – Arun P Johny May 21 '15 at 08:04
  • 1
    I'm not sure why you've crossed out the `tigger()` version of the code - as that is the best solution. – Rory McCrossan May 21 '15 at 08:04
  • possible duplicate of [Javascript: "onchange" event does not work with "value" change in "text input" object](http://stackoverflow.com/questions/6826707/javascript-onchange-event-does-not-work-with-value-change-in-text-input-o) – Siguza May 21 '15 at 08:05
  • I can not change the existing code. values in input change dynamically and on change in input i want to perform some action – ozil May 21 '15 at 08:18

2 Answers2

2

From MDN (bolded by me):

The change event is fired for input, select, and textarea elements when a change to the element's value is committed by the user. Unlike the input event, the change event is not necessarily fired for each change to an element's value.

You will need to manually trigger the change event if you are changing the value programmatically.

I suppose if you are hellbent on not manually firing the change event, you could override jQuery's val ($.fn.val) method to do it for you:

var originalVal = $.fn.val;
$.fn.val = function() {
    if(arguments.length) {
       originalVal.apply(this, arguments);
       this.trigger('change');
       return this;
    }
    return originalVal.call(this);
}

http://jsfiddle.net/ybj1zjhk/4/

Rob M.
  • 35,491
  • 6
  • 51
  • 50
0

will fire the alert whenever you type something

 $('#testinput').keyup(function (){
        change();
    });
    function change(){
        alert();
    }
    $('#testinput').val('new val');  

Or you can trigger the change event whenever you do something that requires you to have the change event fire https://jsfiddle.net/owoemcg2/

$('#testinput').change(function (){
    change();
});
function change(){
    alert();
}
$("#mybutton").click(function(){

$('#testinput').val('new val');  
$("#testinput").trigger("change");
});
Jeremy C.
  • 2,405
  • 1
  • 12
  • 28