Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
759 views
in Technique[技术] by (71.8m points)

javascript - What is the easiest way to detect if at least one field has been changed on an HTML form?

I have an HTML form with over 20 fields. I also have a couple of links on the page which will lead the user away from the form... potentially without having saved any changes.

I want to warn (JS confirm) the user onClick of these links if any of the form fields have changed, but I don't want to create a huge switch statement that I then need to maintain as I add new fields to the form. I know how to create a long list of 'if' statements in Javascript, naming each of the fields and checking each value, but I don't want to do that if I can get away with it.

What's the easiest way to check if the user has changed at least one of the field values?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Approach

  1. serialize the form (and all its values) before showing it (jQuery way, Prototype way)
  2. serialize it again in a "onbeforeunload" event handler

If the two don't match, then they must've changed the form, so return a string (eg "You have unsaved data") from your onbeforeunload handler.

This method allows the form fields to evolve while the "confirm if changed" logic remains the same.

Example (mixed javascript and jquery)

var form_clean;

// serialize clean form
$(function() { 
    form_clean = $("form").serialize();  
});

// compare clean and dirty form before leaving
window.onbeforeunload = function (e) {
    var form_dirty = $("form").serialize();
    if(form_clean != form_dirty) {
        return 'There is unsaved form data.';
    }
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...