How to show changed input and select fields with jQuery

Here are a few quick easy jquery functions that will add a class of 'changed' to any input or select box if it is changed, and will remove that class if the value is reset to the default.



        // inputs
        $('form.myForm :input').change(function(){
        var defval = $(this)[0].defaultValue;
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

        // select boxes
        $('form.myForm select').change(function(){
        var defval = $(this).find('option[defaultSelected=true]').val();
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

Note in both cases we use keyup (onkeyup) to trigger the 'change' event. This allows the browser to show the changed class as soon as the user changes the value using a keyboard, rather than 'onblur'.

Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
You might find the jQuery dirtyFields plugin I wrote to be of interest, as it's designed to track form changes and give the user a visual indicator of which form fields have been changed. I have a small website dedicated to it: http://www.thoughtdelimited.org/dirtyFields
# Author Brian Swartzfager | 12/10/09 8:05 AM
blogcfc 5.9.1.002 by raymond camden
contact michael evangelista