How can I serializeArray for unchecked checkboxes?

前端 未结 12 860
耶瑟儿~
耶瑟儿~ 2021-02-05 08:01

How can I modify this example so it can get values from checkboxes that aren\'t checked?

I want all checkboxes to have a value, if it hasn\'t been checked I want to get

12条回答
  •  春和景丽
    2021-02-05 08:31

    Here's how I implemented a simple override of $.serializeArray which fixes the default serialization behaviour for checkboxes, and default behaviour is retained for all other types.

    In the code below, missed checkboxes are injected into the original serialized array. Checkbox state is returned as "true" (instead of "on") or "false" depending on if it is checked or not.

    (function ($) {
        var _base_serializeArray = $.fn.serializeArray;
        $.fn.serializeArray = function () {
            var a = _base_serializeArray.apply(this);
            $.each(this.find("input"), function (i, e) {
                if (e.type == "checkbox") {
                    e.checked 
                    ? a[i].value = "true" 
                    : a.splice(i, 0, { name: e.name, value: "false" })
                }
            });
            return a;
        };
    })(jQuery);
    

    You could customize this to return "on"/"off" or true/false.

    Update: Fixed code based on bug found by @shyammakwana.me.

提交回复
热议问题