简体   繁体   中英

How to get checked checkbox values and store in as a multidimensional array using Jquery?

I have multiple checkboxes and these have values and title attributes. Here titles are represent group So when i check any checkbox they will store as Json multidimensional array.

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 (i want like this:)

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

And When i uncheck checkbox values remove from group of array and when no value checked from group of array Group will be remove.

I did Code :

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

This should be what you're looking for: 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;
};

You can recreate full object each time a checkbox is changed:

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

As Yukulélé mentioned, the particular json you want to obtain is invalid. This is because the curly braces denote a JSON object, and an object cannot have two properties of the same name. Imagine the object:

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

How would you be able to specify which firstname property you wish to obtain?

The following code will give you close the json output you require, using arrays.

$('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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM