Reputation: 11725
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
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();
Upvotes: 3
Reputation: 4350
This is exactly the reason for the jQuery map function.
var Names = $(':checkbox:checked').map(function (value) {
return value.name;
});
Upvotes: 0
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
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
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