将数组中的单个CheckBox值发送到服务器

时间:2015-08-11 11:04:49

标签: javascript jquery arrays

我在表单上有多个复选框,我将提交表单。

  $.fn.serializeObject = function () {
        'use strict';
        debugger;
        var result = {};
        var extend = function (i, element) {
            var node = result[element.name];
            // If node with same name exists already, need to convert it to an array as it
            // is a multi-value field (i.e., checkboxes)
            if ('undefined' !== typeof node && node !== null) {
                if ($.isArray(node)) {
                    node.push(element.value);
                } else {
                    result[element.name] = [node, element.value];
                }
            } else {
                result[element.name] = element.value;
            }
        };
        $.each(this.serializeArray(), extend);
        return result;
    };

和代码就像

  var that = $(this);
  var temp = $(JSON.stringify());
  form_data = that.serializeObject(temp);
  form_data = JSON.stringify(form_data);

一切正常但如果我单击选中一个复选框,那么值就像         "checkboxName":"value1"   如果我选择checkboc的多个值,那么该值就像         "checkboxName":["value1","value2","value3"]

我希望也应该以数组格式选择单个值         "checkboxName":["value1"]

提前致谢。

1 个答案:

答案 0 :(得分:0)

如果您尝试:

$.fn.serializeObject = function () {
    'use strict';
    debugger;
    var result = {};
    var extend = function (i, element) {
        var node = result[element.name];
        // If node with same name exists already, need to convert it to an array as it
        // is a multi-value field (i.e., checkboxes)
        if ('undefined' !== typeof node && node !== null) {
            if ($.isArray(node)) {
                node.push(element.value);
            } else {
                result[element.name] = [node, element.value];
            }
        } else {
            //Here you are the checkbox condition
            if(element.tagName == "INPUT" && element.getAttribute("type") == "checkbox") {
                  result [element.name] = [element.value];
            } else {
                  result[element.name] = element.value;
            }
        }
    };
    $.each(this.serializeArray(), extend);
    return result;
};