learning
learning

Reputation: 11725

Find and read all checked checkboxes and push their names in an array

I have multiple checkBoxes on my page and using javascript I want to find all checked boxes and push their repective names in an array as follows:

    var Names = new Array();
 $.each($(':checked'), function (key, value) {
 Name.push($(value).attr("name"));
 }); 

What is wrong with the above code?

Upvotes: 1

Views: 5407

Answers (5)

Felix Kling
Felix Kling

Reputation: 816452

A more "functional" way:

var names = $('input[type="checkbox"]:checked').map(function() {
    return this.name;
}).get();

Or maybe it is better to not use the :checked pseudo selector so that jQuery can make better use of the browser functions:

var names = $('input[type="checkbox"]').map(function() {
    if(this.selected) {
        return this.name;
    }
    return null;
}).get();

Reference: .map, .get

Upvotes: 3

Sergei Golos
Sergei Golos

Reputation: 4350

This is exactly the reason for the jQuery map function.

var Names = $(':checkbox:checked').map(function (value) {
     return value.name;
 }); 

Upvotes: 0

David Houde
David Houde

Reputation: 4778

 var Names = new Array();
 $.each($('input:checked'), function (key, value) {
 Names.push($(value).attr("name"));
 }); 

You are using Name, and Names -- 2 different uh..names

Upvotes: 0

orlp
orlp

Reputation: 117691

You can't just select by pseudoelement: :checked. You must select all <input type="checkbox"> elements that are checked:

var Names = new Array();
$.each($('input[type="checkbox"]:checked'), function (key, value) {
    Name.push($(value).attr("name"));
}); 

Upvotes: 1

CoolEsh
CoolEsh

Reputation: 3154

var Names = new Array();
 $(':checkbox:checked').each( function (key, value) {
     Name.push($(value).attr("name"));
 }); 

or even easier:

var Names = new Array();
$(':checkbox:checked').each( function () {
    Name.push( $( this ).attr( "name" ) );
}); 

Upvotes: 1

Related Questions