Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery to monitor form field changes

Trying to learn some jquery to implement an autosave feature and need some assistance. I have some code to monitor the status of form fields to see if there has been any change. Everything works, but I need to only monitor the changes in a specific form, not all form inputs on the page. There is a search box and a newsletter form on the same page and when these form fields are changed, they are detected as well, which I need to filter out somehow or better yet, only target the specific form.

$(function(){
    setInterval("CheckDirty()",10000);
    $(':input').each(function() {
        $(this).data('formValues', $(this).val());
    });
});

function CheckDirty()
{
    var isDirty = false;

    $(':input').each(function () {
        if($(this).data('formValues') != $(this).val()) {
            isDirty = true;
        }
    });

    if(isDirty == true){
        alert("isDirty=" + isDirty);
    }
}
like image 871
Mark Avatar asked Apr 29 '11 10:04

Mark


1 Answers

Just add a class to the form and use it to filter

$('.form :input').each(function() {
    $(this).data('formValues', $(this).val());
});

EDIT

Just a suggestion, you can attach the change event directly to the form

live demo here : http://jsfiddle.net/jomanlk/kNx8p/1/

<form>
    <p><input type='text'></p>
    <p><input type='text'></p>
    <p><input type='checkbox'></p>
</form>

<p><input type='text'></p>

<div id='log'></div>

$('form :input').change(function(){
   $('#log').prepend('<p>Form changed</p>')
});

You can easily improve this by adding a timer and making it save every xx seconds.

like image 157
JohnP Avatar answered Oct 09 '22 15:10

JohnP