Select/submit only changed form fields with jQuery

前端 未结 8 1567
谎友^
谎友^ 2020-12-23 10:45

I\'m looking for a way to submit only changed form fields to the server. So, let\'s say I have a form

相关标签:
8条回答
  • 2020-12-23 11:26

    The simplest solution would be to add something like:

    $(function() {
    
        $("input, select").change(function() {
            $(this).addClass("changed");
        });
    
    });
    

    Then just select on the .changed class to get the elements that have been changed.

    More information on the jQuery change event: http://api.jquery.com/change/

    As @Martin points out below, the change event is only triggered for text inputs after they click off the input. If this is just to save some bandwidth, I would recommend binding on the click event instead. You may get sent some fields that haven't actually changed, but probably better to air on the side of getting too much back than too little.

    0 讨论(0)
  • 2020-12-23 11:35

    You could try adding a class to each field which has been changed and remove the others prior to calling $('form').serialize().

    $(function() {
        $(':input').change(function() {
            $(this).addClass('changed');
        });
        $('form').submit(function () {
            $('form').find(':input:not(.changed)').remove();
            return true;
        });
    });
    

    Though this solution is destructive and only works if you're not using AJAX (a solution exists even for AJAX but it gets even more complicated).

    0 讨论(0)
提交回复
热议问题