Search code examples
javascriptjqueryhtmlformsonchange

Find out if html form has changed


Using jquery I've added a change handler to a form. This works when any input is changed BUT only if the user manually changes an input and not when some other code changes the input.

Is there any way to detect if a form has changed even if its inputs are changed by code?


Solution

  • Yes, there seems to be some confusion over this. In an ideal world you would expect the onchange event to happen whenever the inputs change but thats not what happens. I'm sure for good reasons to - maybe not.

    One way I've overcome this obstacle is to capture the form state into a variable just after displaying it and then just before submitting it to check if the state has changed and to act accordingly.

    An easy state to store is what the serialize function returns. An easy place to store the state is using the data functionality. Both serialize and data are available with jquery.

    Of course you can use other different forms of state (some form of hash) or storage for this state (standard global variable for example).

    Here is some prototype code:

    If your form id is 'xform' then you can call the following code when the form has displayed:

    $('#xform').data('serialize',$('#xform').serialize());
    

    And then, when you need to check, for example just before a button submit you can use:

    if($('#xform').serialize()!=$('#xform').data('serialize')){
        // Form has changed!!!
    }
    

    You could wrap all this up into a copy & paste javascript snippet that will give you a formHasChanged() function to call wherever you need it (NOT TESTED):

    $(function() {
        $('#xform').data('serialize',$('#xform').serialize());
    });
    function formHasChanged(){
        if($('#xform').serialize()!=$('#xform').data('serialize')){
            return(true);
        }
        return(false);
    }
    

    But I'll stop here otherwise I'll create yet another jquery plugin.