how can I override jquery's .serialize to include unchecked checkboxes

后端 未结 10 890
暖寄归人
暖寄归人 2020-12-16 14:21

I have read quite a few different methods of having html checkboxes get posted to the server, but I am really looking to do it without modifying anything except for $.serial

10条回答
  •  渐次进展
    2020-12-16 14:53

    Beetroot-Beetroot's answer did not work for me in jQuery 1.9 and later. I used .val() and .prop(), and got rid of the .eq(0) requirement on the container, which restricted serializing to one form in the selector. I had a rare case where I had to serialize multiple forms at the same time, so removing that requirement solved that. Here's my modified solution:

    $.fn.mySerialize = function(options) {
        // default values to send when checkbox is on or off
        var settings = {
            on: 'on',
            off: 'off'
        };
    
        // override settings if given
        if (options) {
            settings = $.extend(settings, options);
        }
    
        // set all checkboxes to checked with the on/off setting value
        // so they get picked up by serialize()
        var $container = $(this),
            $checkboxes = $container.find("input[type='checkbox']").each(function() {
                $(this).val(this.checked ? settings.on : settings.off).prop('checked', true);
            });
    
        var serialized = ($container.serialize());
    
        $checkboxes.each(function() {
            var $this = $(this);
            $this.prop('checked', $this.val() == settings.on);
        });
    
        return serialized;
    };
    

    You can see the corresponding fiddle here.

提交回复
热议问题