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,946
  • 7
  • 40
  • 73
web dev
  • 305
  • 1
  • 5
  • 17

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
  • 23,450
  • 12
  • 63
  • 93
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,567
  • 1
  • 16
  • 26
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
  • 85,780
  • 21
  • 159
  • 179