javascript 如何为未选中的复选框序列化数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7335281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:45:28  来源:igfitidea点击:

How can I serializeArray for unchecked checkboxes?

javascriptjqueryforms

提问by BrunoLM

How can I modify this exampleso 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 its value as false.

我希望所有复选框都有一个值,如果尚未选中,我想将其值设为false.

<input type="checkbox" name="Check01" value="true" />
<input type="checkbox" name="Check02" value="true" checked="checked" />

Default behavior

默认行为

$("form").serializeArray();
// [Check02 = true]

Expected behavior

预期行为

$("form").serializeArray();
// [Check01 = false, Check02 = true]

采纳答案by Pointy

It's probably easiest to just do it yourself:

自己做可能最简单:

 var serialized = $('input:checkbox').map(function() {
   return { name: this.name, value: this.checked ? this.value : "false" };
 });

If there are other inputs, then you could serialize the form, and then find the unchecked checkboxes with something like the above and append that result to the first array.

如果还有其他输入,那么您可以序列化表单,然后使用类似上述内容找到未选中的复选框,并将该结果附加到第一个数组。

回答by ShankarSangoli

serializeArrayignores the checkboxes which are not checked.You can try something like this.

serializeArray忽略未选中的复选框。你可以尝试这样的事情。

Working demo

工作演示

    var serializedObj = {};
    $("form input:checkbox").each(function(){
        serializedObj[this.name] = this.checked;
    });

回答by tang wei

you can use this get unchecked values

您可以使用此获取未选中的值

$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
var $radio = $('input[type=radio],input[type=checkbox]',this);
$.each($radio,function(){
    if(!o.hasOwnProperty(this.name)){
        o[this.name] = '';
    }
});
return o;
};

code samples

代码示例

回答by Ben

another option is to just look at the source code for serializeArray and remove (or modify) the call to filter. I Just took that function and created a new one called serializeArrayAll like this:

另一种选择是查看 serializeArray 的源代码并删除(或修改)对过滤器的调用。我刚刚使用了该函数并创建了一个名为 serializeArrayAll 的新函数,如下所示:

$.fn.serializeArrayAll = function() {
var rCRLF = /\r?\n/g;
return this.map(function(){
    return this.elements ? jQuery.makeArray( this.elements ) : this;
})
/* this is what is excluding the unchecked checkboxes (and also other disabled options) 
    .filter(function(){
        return this.name && !this.disabled &&
            ( this.checked || rselectTextarea.test( this.nodeName ) ||
                rinput.test( this.type ) );
    })
 */
    .map(function( i, elem ){
        var val = jQuery( this ).val();

        return val == null ?
            null :
            jQuery.isArray( val ) ?
                jQuery.map( val, function( val, i ){
                    return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                }) :
            { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
    }).get();

};

};

回答by tothemario

Using the jQuery plugin serializeJSON, you can use the data-unchecked-valueattribute to specify the value when unchecked:

使用 jQuery 插件serializeJSON,您可以使用该data-unchecked-value属性在未选中时指定值:

<input type="checkbox" name="Check01" value="true" data-unchecked-value="false" />
<input type="checkbox" name="Check02" value="true" data-unchecked-value="false" checked="checked" />

JavaScript:

JavaScript:

$('input').serializeJSON({ parseBooleans: true });
// returns => { 'Check01' : false, 'Check02' : true }

回答by Johnny Oshika

you can add a hidden false value for every checkbox:

您可以为每个复选框添加一个隐藏的 false 值:

<input type="checkbox" name="Check01" value="true" /><input name="Check01" type="hidden" value="false" />
<input type="checkbox" name="Check02" value="true" checked="checked" /><input name="Check02" type="hidden" value="false" />

You will only get "false" values for unchecked checkboxes and both "true" and "false" for checked checkboxes, so you can remove the duplicates like this:

对于未选中的复选框,您只会获得“false”值,而对于选中的复选框,您将获得“true”和“false”值,因此您可以像这样删除重复项:

var params = {};
$.each($('form').serializeArray(), function (index, value) {
    params[value.name] = params[value.name] ? params[value.name] || value.value : value.value;
});
console.log(params); // outputs: {"Check01":"false","Check02":"true"}

回答by SNag

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

这是我如何实现一个简单的覆盖,$.serializeArray它修复了复选框的默认序列化行为,并保留了所有其他类型的默认行为。

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 checkedor not.

在下面的代码中,丢失的复选框被注入到原始序列化数组中。复选框状态返回为"true"(而不是"on")或"false"取决于它是否为checked

(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.

您可以将其自定义为 return"on"/"off"true/false

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

更新:基于@shyammakwana.me 发现的错误修复了代码。

回答by shyammakwana.me

@SNag's answerworker almost 99% just with little bit correction. Change below line

@SNag 的回答人员几乎 99% 只是稍作修正。更改线下

from :

从 :

$.each(this, function (i, e) {

to:

到:

$.each(this.find('input'), function (i, e) {

Explanation: As this was not working because thisreturned form element. So on form .eachwon't give us all input elements inside form. So I did this correction and it worked like charm.

说明:因为这不起作用,因为this返回了表单元素。因此,表单.each不会为我们提供表单内的所有输入元素。所以我做了这个更正,它很有魅力。

回答by yk4ever

You can append unchecked checkbox data to .serializeArrayresult:

您可以将未选中的复选框数据附加到.serializeArray结果中:

var formData = $("#mybaseelement").serializeArray();
$('#mybaseelement input[type="checkbox"]:not(:checked)').each(function(i, e) {
    formData.push({name: e.getAttribute("name"), value: false});
});

This is the least invasive solution I can come up with.

这是我能想出的侵入性最小的解决方案。

回答by picomp

I made my own new solution based on the answers by @Pointy, @Ben, and the original jQuery code. The answer from @Pointy had odd behavior that returned contexts for checkboxes, this fixes that problem. The answer from @Ben was also not acting properly because it always returned checkbox = oneven if it was unchecked.

我根据@Pointy、@Ben 和原始 jQuery 代码的答案制作了自己的新解决方案。@Pointy 的答案有奇怪的行为,返回复选框的上下文,这解决了这个问题。@Ben 的回答也没有正确运行,因为checkbox = on即使未选中它也总是返回。

$.fn.serializeArrayWithCheckboxes = function() {
var rCRLF = /\r?\n/g;
return this.map(function(){
    return this.elements ? jQuery.makeArray( this.elements ) : this;
})

    .map(function( i, elem ){
        var val = jQuery( this ).val();


        if (val == null) {
          return val == null
        //next 2 lines of code look if it is a checkbox and set the value to blank 
        //if it is unchecked
        } else if (this.type == "checkbox" && this.checked == false) {
          return { name: this.name, value: this.checked ? this.value : ""}
        //next lines are kept from default jQuery implementation and 
        //default to all checkboxes = on
        } else {
          return jQuery.isArray( val ) ?
                jQuery.map( val, function( val, i ){
                    return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
                }) :
            { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
        }
    }).get();
};