getting the names of elements in JS/jQuery
I have some checkbox inputs like so:
<input type="checkbox" name="1" class="filter"/>
<开发者_如何学Goinput type="checkbox" name="2" class="filter"/>
...etc...
I'm trying to write a function where any time a checkbox is selected, it generates a string with all the names concatenated. Here's what I have so far:
$('.filter').click(function(event){
var filters = $('.filter').toArray();
var fstr = "";
for (f in filters)
{
fstr = fstr+","+f.name;
}
alert(fstr);
});
The names keep coming up as 'undefined', though (i.e. the alert returns ,undefined,undefined,undefined,undefined,undefined,undefined
). How do I access the names?
Here's how it's meant to be done:
$('.filter').click(function (event)
{
var fstr = '';
$('.filter[name]').each(function ()
{
fstr += ',' + $(this).attr('name');
});
alert(fstr);
});
You can use .map()
to get what you're after, like this:
$('.filter').click(function(event){
var names = $('.filter').map(function () {
return $(this).attr("name");
}).get().join(',');
alert(names);
});
Just change $('.filter')
to $('.filter:checked')
if you want a list containing only the checked ones.
$('.filter').click(function(event){
var filters = $('.filter').toArray();
var fstr = "";
for (f in filters)
{
fstr = fstr+","+filters[f].name;
}
alert(fstr);
});
Why are you doing it that way anyway?
$('.filter').click(function(event){
var str = '';
$('.filter').each(function () {
str += $(this).attr('name') +",";
});
alert(str);
});
(function($filters) {
$filters.click(function(event) {
var filters = $filters.toArray();
var fstr = [];
for (var i = filters.length - 1; i > -1; --i) {
fstr.push(filters[i].name);
}
fstr = fstr.join(",");
alert(fstr);
}
})($('.filter'));
Try $(f).name
.
How about $(elem).attr("name")
?
I'm thinking the convert to array is your problem, try:
var filters = $('.filter');
for(var nI = 0; nI < filters.length; nI++)
filters.eq(nI).attr('name');
精彩评论