如何获取复选框值并使用Jquery作为多维数组存储?

时间:2016-05-19 13:45:51

标签: javascript php jquery arrays checkbox

我有多个复选框,它们具有值和标题属性。 这里的标题代表组所以当我检查任何复选框时,它们将存储为Json多维数组。

Html:

<span>
    <input type="checkbox" value="4" title="23">
    <input type="checkbox" value="5" title="23">
    <input type="checkbox" value="2" title="24">
</span>
<output id="hsearchData"></output>

Json Code(我想要这样:):

[
    "23":{
        "id":"4",
        "id":"5"
    },
    "24":{
        "id":"2"
    }
]

当我取消选中复选框值时,从数组中删除,并且不会删除从数组Group中检查的值。

我做了代码:

$('span').find('input[type=checkbox]').click(function(event) {
        var searchData = $('input:checkbox:checked').map(function() {
            return this.value;
        }).get();
        $("#hsearchData").val(searchData);
});

3 个答案:

答案 0 :(得分:0)

这应该是你正在寻找的: JsFiddle

<强>的Javascript

var json = {};

$('input[type="checkbox"]').change(function() {
  var title = $(this).attr('title');
  var id = $(this).val();
  var prop = $(this).is(':checked');
    if (prop) {
    if (typeof json[title] === 'undefined') {
        json[title] = [id];
    } else {
      json[title].push(id);
    }
  } else {
    json[title].remove(id);
    if(!json[title].length) { delete json[title] }
  }

  console.log(json);
});

Array.prototype.remove = function() {
    var what, a = arguments, L = a.length, ax;
    while (L && this.length) {
        what = a[--L];
        while ((ax = this.indexOf(what)) !== -1) {
            this.splice(ax, 1);
        }
    }
    return this;
};

答案 1 :(得分:0)

每次更改复选框时都可以重新创建完整对象:

var wrapper = $('span')
var inputs = wrapper.find('input[type=checkbox]')
var checked = {}
wrapper.on('change', function (event) {
  checked = {}
  inputs.each(function (k, v) {
    (checked[this.title] = checked[this.title] || []).push(this.value)
  })
console.log(checked)
}).trigger('change')

答案 2 :(得分:0)

正如Yukulélé所提到的,您想要获得的特定json无效。这是因为花括号表示JSON对象,而对象不能具有两个相同名称的属性。想象一下这个对象:

var person = {firstName:"John", firstname:"Henry"}

您如何指定您希望获得的名字属性?

以下代码将使您使用数组关闭所需的json输出。

$('span').find('input[type=checkbox]').click(function(event) {
    var values = {};
    $('input:checkbox:checked').each(function() {
        if (values[this.title])
          values[this.title].push({ id: this.value });
        else
          values[this.title] = [{ id: this.value }];
    });


    $("#hsearchData").val(JSON.stringify(values));
});

http://jsbin.com/giqevineya/edit?html,css,js,console,output