Trigger ‘onchange’ event when value changes. (jQuery)

You’d think that when you changed a value in a form input, the browser would fire the “onchange” event for that element. This is partially true. It will do so if a user changes the value, but not if it’s changed programmatically via JavaScript. So I needed some JavaScript (irony?), and here’s what I found:

And here’s what I used (with a new function name, while leaving .val() alone):

$.fn.valChange = function(){
    var prev;
    if ( arguments.length > 0 ){
        prev = $.fn.val.apply(this, []);
    var result = $.fn.val.apply(this, arguments);
    if ( arguments.length > 0 && prev != $.fn.val.apply(this, []) ){
    return result;

And here’s how to implement it:


<input type="text" id="test" value="Test">
<button id="btn1">Button 1</button>
<button id="btn2">Button 2</button>


// send a log message to the console when it changes
    console.log("The value has changed");
$("#btn1, #btn2").click(function(){
    // set the value when clicking the buttons
    // and if it's different than it was,
    // trigger the "onchange" event for the input

And here’s the obligatory JSFiddle to go with it:


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s