Detecting data changes in forms using jQuery

后端 未结 10 1989
遇见更好的自我
遇见更好的自我 2020-12-05 13:27

I\'m using ASP.NET 2.0 with a Master Page, and I was wondering if anyone knew of a way to detect when the fields within a certain

or fieldset<
相关标签:
10条回答
  • .live is now deprecated and replaced by .on:

    var confirmerSortie = false;
    $(document).on('change', 'select', function() {
        confirmerSortie = true;
    });
    
    $(document).on('change keypress', 'input', function() {
        confirmerSortie = true;
    });
    
    $(document).on('change keypress', 'textarea', function() {
        confirmerSortie = true;
    });
    
    0 讨论(0)
  • 2020-12-05 14:22

    I came up with this piece of code in CoffeeScript (not really field tested, yet):

    • Add class 'change_warning' to forms that should be watched for changes.

    • Add class 'change_allowed' to the save button.

    change_warning.coffee:

    window.ChangeWarning = {
        save: ->
            $(".change_warning").each (index,element) ->
                $(element).data('serialized', $(element).serialize())
    
        changed: (element) ->
            $(element).serialize() != $(element).data('serialized')
    
        changed_any: ->
            $.makeArray($(".change_warning").map (index,element) -> ChangeWarning.changed(element)).some (f)->f
            # AKA $(".change_warning").any (element) -> ChangeWarning.changed(element)
            # But jQuery collections do not know the any/some method, yet (nor are they arrays)
    
        change_allowed: ->
            ChangeWarning.change_allowed_flag = true
    
        beforeunload: ->
            unless ChangeWarning.change_allowed_flag or not ChangeWarning.changed_any()
                "You have unsaved changes"
    }
    
    $ ->
        ChangeWarning.save()
        $(".change_allowed").bind 'click', -> ChangeWarning.change_allowed()
        $(window).bind 'beforeunload',     -> ChangeWarning.beforeunload()
    
    0 讨论(0)
  • 2020-12-05 14:25

    Just to clarify because the question is "within a certain fieldset/div":

    var somethingChanged = false;
    $(document).ready(function() { 
       $('fieldset > input').change(function() { 
            somethingChanged = true; 
       }); 
    });
    

    or

    var somethingChanged = false;
    $(document).ready(function() { 
       $('div > input').change(function() { 
            somethingChanged = true; 
       }); 
    });
    
    0 讨论(0)
  • 2020-12-05 14:27

    A simple and elegant solution (it detects form elements changes in real time):

    var formChanged = false;
    
    $('#my-div form').on('keyup change paste', 'input, select, textarea', function(){
        formChanged = true;
    });
    
    0 讨论(0)
提交回复
热议问题