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.

5
  • $(elem).val('text') doesn't trigger a change. See this post: stackoverflow.com/questions/3179385/… Commented May 21, 2015 at 8:04
  • If you change teh value programatically the change event won't be triggered, So I guess you no choice but to use tigger Commented May 21, 2015 at 8:04
  • 1
    I'm not sure why you've crossed out the tigger() version of the code - as that is the best solution. Commented May 21, 2015 at 8:04
  • possible duplicate of Javascript: "onchange" event does not work with "value" change in "text input" object Commented May 21, 2015 at 8:05
  • I can not change the existing code. values in input change dynamically and on change in input i want to perform some action Commented May 21, 2015 at 8:18

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

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");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.