Mala
Mala

Reputation: 14843

getting the names of elements in JS/jQuery

I have some checkbox inputs like so:

<input type="checkbox" name="1" class="filter"/>
<input 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?

Upvotes: 0

Views: 107

Answers (7)

Pablo Cabrera
Pablo Cabrera

Reputation: 5849

(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'));

Upvotes: 1

Matt
Matt

Reputation: 75327

$('.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);
});

Upvotes: 1

aepheus
aepheus

Reputation: 8197

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');

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630589

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.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359966

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

Upvotes: 4

Jeriko
Jeriko

Reputation: 6637

How about $(elem).attr("name")?

Upvotes: 0

Millions
Millions

Reputation: 300

Try $(f).name.

Upvotes: 0

Related Questions