本文介绍了检测HTML表单中是否至少有一个字段已被更改的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超过20个字段的HTML表单。我也有一些在页面上的链接,这将导致用户远离表单...可能没有保存任何更改。



我想警告(JS确认)用户onClick这些链接是否有任何表单字段发生了变化,但我不想创建一个巨大的switch语句,然后在向表单中添加新字段时需要维护这些语句。我知道如何在Javascript中创建一个'if'语句的长列表,命名每个字段并检查每个值,但如果我可以避开它,我不想这样做。



检查用户是否至少改变了一个字段值的最简单方法是什么?

解决方案

http://docs.jquery.com/Ajax/serializerel =noreferrer> jQuery方式,)

  • 在事件处理程序

  • 两者不匹配,那么他们必须改变形式,所以从 onbeforeunload 处理程序中返回一个字符串(例如您有未保存的数据)。



    此方法允许表单字段在确认如果更改逻辑保持不变的情况下进化。



    示例 (混合javascript和jquery)

      var form_clean; 
    $ b $ //序列化干净表单
    $(function(){
    form_clean = $(form)。serialize();
    });

    //在离开
    之前比较干净和脏的表单window.onbeforeunload = function(e){
    var form_dirty = $(form)。serialize();
    if(form_clean!= form_dirty){
    return'有未保存的表单数据。';
    }
    };


    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?

    解决方案

    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.';
        }
    };
    

    这篇关于检测HTML表单中是否至少有一个字段已被更改的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-01 03:11