0

I want to store the checked checkbox value and it's name in a two dimensional array, here is html code.

<h3>Select your favorite sports:</h3>
<label>
    <input type="checkbox" value="football" name="football"> Football</label>
<label>
    <input type="checkbox" value="baseball" name="baseball"> Baseball</label>

And I can only display the checked checbox values, here is jQuery code

$(document).ready(function () {
    $("button").click(function () {
        var favorite = [];
        $.each($("input:checked"), function () {
            favorite.push($(this).val());
        });
        alert("My favourite sports are: " + favorite);
    });
});

My question is how to store both values and It's name in favorite array?

aurelius
  • 3,454
  • 6
  • 32
  • 65
web dev
  • 137
  • 4
  • 12

3 Answers3

2

You can use Array of objects for this:

favorite.push({
   name: $(this).attr('name'),
   value:$(this).val()
});

See it in action

Output:

[{
    "name": "football",
    "value": "football"
}, {
    "name": "baseball",
    "value": "baseball"
}]

If you want to display values:

$.each(favorite, function(index, obj){
   console.log("Name= "+ obj.name+"  Value="+ obj.value);
})
Community
  • 1
  • 1
Manwal
  • 22,117
  • 10
  • 57
  • 89
1

use map().Translate all items in an array or object

var favorite= $("input:checked").map(function () {
    var obj = {};
    obj[$(this).attr('name')] = this.value;
    return obj;

}).get();

console.log(favorite)

DEMO

Balachandran
  • 9,277
  • 1
  • 13
  • 25
1

Use array of objects

$(document).ready(function () {
    $("button").click(function () {
        var favorite = [];
        $.each($("input:checked"), function () {

            // Add object in array
            favorite.push({
                name: $(this).attr('name'),
                value: $(this).val()
            });
        });
        console.log("My favourite sports are: ");
        console.log(favorite);
    });
});
Tushar
  • 78,625
  • 15
  • 134
  • 154