views:

51

answers:

7

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?

A: 

Try $(f).name.

J.Milly
still undefined
Mala
A: 

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

Jeriko
also still undefined...
Mala
By `elem` i mean any element. So in this case you'd use `$(f)`... - still undefined?
Jeriko
He's using `for in`, `f` is simply the property's key, not value.
Matt
+4  A: 

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);
});
Matt Ball
Thank you! I was trying to figure out the proper jquery syntax, and what's more this one actually works :)
Mala
There is no `.name()` method, you have to get the name like any other attribute, using `.attr()`. You may have seen `.val()` used, but that is a special function primarily for getting the logical value of form elements.
Matt Ball
+1  A: 

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.

Nick Craver
A: 

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');
aepheus
+1  A: 
$('.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);
});
Matt
+1  A: 
(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'));
Pablo Cabrera