jQuery 序列化不注册复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3029870/
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-08-26 14:45:23  来源:igfitidea点击:

jQuery serialize does not register checkboxes

jqueryserialization

提问by Steven

I'm using jQuery.serialize to retrieve all data fields in a form.

我正在使用 jQuery.serialize 来检索表单中的所有数据字段。

My problem is that it does not retriev checkboxes that is not checked.

我的问题是它不会检索未选中的复选框。

It includes this:

它包括:

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" checked="checked" />

but not this

但不是这个

<input type="checkbox" id="event_allDay" name="event_allDay" class="checkbox" />

How can I get "values" of checkboxes that is not checked?

如何获取未选中的复选框的“值”?

采纳答案by Andy E

jQuery serializeclosely mimics how a standard form would be serialized by the browser before being appended to the query string or POST body in the request. Unchecked checkboxes aren't included by the browser, which makes sense really because they have a boolean state -- they're either selected by the user (included) or not selected by the user (not included).

jQueryserialize密切模仿标准表单在附加到请求中的查询字符串或 POST 正文之前如何由浏览器序列化。浏览器不包含未选中的复选框,这确实有意义,因为它们具有布尔状态——它们要么由用户选择(包含),要么未被用户选择(不包含)。

If you need it to be in the serialized, you should ask yourself "why? why not just check for its existence in the data?".

如果你需要它在序列化中,你应该问自己“为什么?为什么不检查它在数据中的存在?”。

Bear in mind that if the way JavaScript serializes form data behaves differently to the way the browser does it then you're eliminating any chance of graceful degradation for your form. If you still absolutely need to do it, just use a <select>box with Yes/No as options. At least then, users with JS disabled aren't alienated from your site and you're not going against the defined behaviour in the HTML specification.

请记住,如果 JavaScript 序列化表单数据的方式与浏览器的行为方式不同,那么您就消除了表单优雅降级的任何机会。如果您仍然绝对需要这样做,只需使用<select>带有 Yes/No 选项的框即可。至少,禁用 JS 的用户不会与您的站点疏远,并且您不会违反 HTML 规范中定义的行为。

<select id="event_allDay" name="event_allDay">
   <option value="0" selected>No</option>
   <option value="1">Yes</option>
</select>

I've seen this employed on some sites in the past and always thought to myself, "why don't they just use a checkbox"?

我过去曾在某些网站上看到过这种情况,并且一直在想,“他们为什么不使用复选框”

回答by mydoghasworms

To build on azatoth's genius answer, I have slightly extended it for my scenario:

为了建立 azatoth 的天才答案,我针对我的场景稍微扩展了它:

    /* Get input values from form */
    values = jQuery("#myform").serializeArray();

    /* Because serializeArray() ignores unset checkboxes and radio buttons: */
    values = values.concat(
            jQuery('#myform input[type=checkbox]:not(:checked)').map(
                    function() {
                        return {"name": this.name, "value": false}
                    }).get()
    );

回答by azatoth

You don't, as serialize is meant to be used as an query string, and in that context, unchecked means it's not in the querystring at all.

你不这样做,因为序列化旨在用作查询字符串,在这种情况下,未选中意味着它根本不在查询字符串中。

If you really want to get the values of unchecked checkboxes, use: (untested off course)

如果您真的想获取未选中复选框的值,请使用:(未经测试当然)

var arr_unchecked_values = $('input[type=checkbox]:not(:checked)').map(function(){return this.value}).get();

回答by Mazatec

if you want to add unserialized checkboxes to your query string, add the following to your jquery submit function:

如果要将未序列化的复选框添加到查询字符串中,请将以下内容添加到 jquery 提交函数中:

var moreinfo = '';

$('input[type=checkbox]').each(function() {     
    if (!this.checked) {
        moreinfo += '&'+this.name+'=0';
    }
});

回答by Fury

jQuery serialize gets the value attribute of inputs.

jQuery 序列化获取输入的 value 属性。

Now how to get checkbox and radio button to work? If you set the click event of the checkbox or radio-button 0 or 1 you will be able to see the changes.

现在如何让复选框和单选按钮工作?如果您将复选框或单选按钮的点击事件设置为 0 或 1,您将能够看到更改。

$( "#myform input[type='checkbox']" ).on( "click", function(){
     if ($(this).prop('checked')){
          $(this).attr('value', 1);
     } else {
          $(this).attr('value', 0);
     }
 }); 

 values = $("#myform").serializeArray();

and also when ever you want to set the checkbox with checked status e.g. php

以及当您想设置复选框时检查状态,例如 php

<input type='checkbox' value="<?php echo $product['check']; ?>" checked="<?php echo $product['check']; ?>" />

回答by bigp

Here's another solution that extends the "serializeArray" method (while preserving the original behavior).

这是扩展“serializeArray”方法的另一个解决方案(同时保留原始行为)。

//Store the reference to the original method:

var _serializeArray = $ji.fn.serializeArray;

var _serializeArray = $ji.fn.serializeArray;

//Now extend it with newer "unchecked checkbox" functionality:
$ji.fn.extend({
    serializeArray: function () {
        //Important: Get the results as you normally would...
        var results = _serializeArray.call(this);

        //Now, find all the checkboxes and append their "checked" state to the results.
        this.find('input[type=checkbox]').each(function (id, item) {
            var $item = $ji(item);
            var item_value = $item.is(":checked") ? 1 : 0;
            var item_name = $item.attr('name');
            var result_index = null;
            results.each(function (data, index) {
                if (data.name == item_name) {
                    result_index = index;
                }
            });

            if (result_index != null) {
                // FOUND replace previous value
                results[result_index].value = item_value;
            }
            else {
                // NO value has been found add new one
                results.push({name: item_name, value: item_value});
            }
        });
        return results;
    }
});

This will actually append "true" or "false" boolean results, but if you prefer you can use "1" and "0" respectively, by changing the value to value: $item.is(":checked") ? 1 : 0.

这实际上会附加“true”或“false”布尔结果,但如果您愿意,可以分别使用“1”和“0”,将值更改为value: $item.is(":checked") ? 1 : 0.

Usage

用法

Just as usual, call the method on your form: $form.serialize()or $form.serializeArray(). What happens is that serializemakes use of serializeArrayanyways, so you get the proper results (although different format) with whichever method you call.

像往常一样,调用表单上的方法:$form.serialize()$form.serializeArray()。发生的情况是无论如何serialize都使用它serializeArray,因此无论您调用哪种方法,您都可以获得正确的结果(尽管格式不同)。

回答by Cefn Hoile

A technique I've used in my own systems, and which I believe is employed by Struts, is to include...

我在自己的系统中使用过的一种技术,我相信 Struts 采用了这种技术,它包括...

<input type="hidden" name="_fieldname" value="fieldvalue"/> 

...immediately next to the checkbox as part of my form creation logic.

...作为我的表单创建逻辑的一部分,紧邻复选框。

This allows me to reconstruct which checkboxes were served in the form but not selected, with a tiny bit of extra logic to do the diff what was served and what was checked, you have the ones which were unchecked. The submission is also the same in content regardless whether you're using HTML or AJAX style submission.

这使我可以重建哪些复选框在表单中提供但未选中,并使用一点额外的逻辑来区分提供的内容和选中的内容,您有未选中的复选框。无论您使用 HTML 还是 AJAX 样式提交,提交的内容也是相同的。

Depending on the technology you're using server-side then you may wish to use this syntax...

根据您使用的服务器端技术,您可能希望使用此语法...

<input type="hidden" name="_fieldname[]" value="fieldvalue"/>

...to make it easy to grab these values as a list.

...以便轻松获取这些值作为列表。

回答by Ferhat KO?ER

You can call handleInputs()add in your submit function before ajax

您可以handleInputs()在 ajax 之前在提交函数中调用add

function handleInputs(){
    $('input[type=checkbox]').each(function() {     
        if (!this.checked) {
            $(this).attr("value","0");
        }else{
            $(this).attr("value","1");
        }
    });
}

It is perfectly working

它完美地工作

回答by Jecoms

This will set your form checkbox values to booleans using their checked state.

这将使用它们的选中状态将您的表单复选框值设置为布尔值。

var form = $('#myForm');
var data = form.serializeObject();

$('#myForm input[type=checkbox]').each(function() { data[this.name] = this.checked; });

The framework we use creates two inputs with the same name, which leads to unexpected behavior when serializing the form. I would get each checkbox value parsed as a two-element array with string values. Depending on how you map data server-side, you may get unintended results.

我们使用的框架创建了两个同名的输入,这会导致在序列化表单时出现意外行为。我会将每个复选框值解析为带有字符串值的二元素数组。根据您映射数据服务器端的方式,您可能会得到意想不到的结果。

回答by iCode

For ASP.NET MVC, we successfully save a form with checkboxesvia an AJAXPOST with the following, which is a combination of several methods referenced in this post, including @Jecoms suggestion:

对于ASP.NET MVC,我们通过AJAXPOST成功保存了一个带有复选框的表单,如下所示,这是本文中引用的几种方法的组合,包括@Jecoms 建议

var form = $('#myForm');
// Serialize the form into a JavaScript object using the jQuery.serializeObject plugin
// https://plugins.jquery.com/serializeObject/
var data = form.serializeObject();
// Change the submitted value of checkboxes to the value of the checked property
$('#myForm input[type=checkbox]').each( function () { data[this.name] = this.checked; } );
// For a MVC controller, convert the JS object back into a query string using jQuery.param function
data = $.param(data);
// Perform AJAX POST with the form data
$.ajax({
    async: true,
    url: 'mvcActionMethodURL',
    type: 'POST',
    data: data,
    success: function (data, textStatus, xhr) {

    },
    error: function (xhr, status, error) {

    }
});