Leveraging the OnChange Event of Inputs with jQuery

If you're new here, you may want to subscribe to my RSS feed or follow me on Twitter. Thanks for visiting!

This may be obvious, but it’s something that’s easily overlooked. Text inputs, like select fields, have an onChange handler that can be leveraged to detect when a field has been (you guessed it…) changed. This may not seem like a big deal, but it really helps when, for example, you’re trying to keep track of which text fields on a page have been updated so you can save them to a database via ajax.

Here’s a nice, simple method to easily detect (and save) inputs that have been modified by leveraging the onChange method of inputs via jQuery:

$(":input").change(function() {
    // save the field's new value
    $.post("save_data.php", { field: $(this).attr('id'), value: $(this).val() });
    }
);

… the nice thing about this method is that you don’t have to track previous and new values since this method will only get triggered if the data has been altered in the textbox. Obviously, this is just an example, but it should serve as a good primer for what’s possible.

(Via Ben Nadel)


About this entry