开发者

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 abov开发者_StackOverflowe code?


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


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"));
}); 


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" ) );
}); 


 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


This is exactly the reason for the jQuery map function.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜