【问题标题】:How to get checked checkbox values and store in as a multidimensional array using Jquery?如何使用 Jquery 获取选中的复选框值并存储为多维数组?
【发布时间】:2016-09-16 10:46:05
【问题描述】:

我有多个复选框,它们具有值和标题属性。 这里的标题代表组所以当我选中任何复选框时,它们将存储为 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 代码(我想要这样的:)

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

当我取消选中复选框值时,从数组组中删除,当没有从数组组中选中值时,将被删除。

我做了代码:

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

【问题讨论】:

  • 您的 json 无效:您不能有 2 个 id 键。但是你可以使用数组:{ 23: [4,5], 24: [2] }

标签: javascript php jquery arrays checkbox


【解决方案1】:

正如 Yukulélé 所说,您想要获取的特定 json 是无效的。这是因为花括号表示一个 JSON 对象,一个对象不能有两个同名的属性。想象一下这个物体:

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

您将如何指定您希望获得的 firstname 属性?

以下代码将使用数组为您关闭所需的 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

【讨论】:

  • 感谢@Ausxor 的宝贵时间。
【解决方案2】:

这应该是您要查找的内容: 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;
};

【讨论】:

    【解决方案3】:

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

    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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 2021-09-04
      • 2020-06-01
      相关资源
      最近更新 更多