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:

http://stackoverflow.com/questions/3179385/val-doesnt-trigger-change-in-jquery

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, []) ){
        $(this).trigger("change");
    }
    return result;
};

And here’s how to implement it:

HTML:

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

JavaScript:

// send a log message to the console when it changes
$("#test").change(function(){
    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
    $("#test").valChange($(this).text());
});

And here’s the obligatory JSFiddle to go with it:
http://jsfiddle.net/fbdskfz9/

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s