tags:

views:

48

answers:

1

I currently have a list of checkboxes all with the same ID which are hidden and I want to grab the list of the ones that are checked, is this possible? I am currently using this format:

selected_list = $("#ID").attr("checked", "true");

this however is only returning the top one when I read them into a variable with a loop like this:

list = '';
$(selected_list).each(
    function() {
          list += $(this).val() + " ";
    } 
);

alert(list);

Anyone know of a better way of doing this or why my version is only returning the first checkbox? Thanks

+3  A: 

You shouldn't re-use ID values, they are supposed to be unique:

$("#elementID:checked");

Ideally, you should give them all the same class, or name, depending on how you want to use them. But you should never use the same ID over and over on a single page.

<input type="checkbox" name="Apples"  class="fruit" />
<input type="checkbox" name="Oranges" class="fruit" />

We can select these various different ways. First, by class:

$(".fruit:checked");

Or simply by a vague checkbox call:

$(":checkbox:checked");

Or, in the case with radio buttons, if they all shared the same name value:

$("[name='elements']:checked");
Jonathan Sampson
what is a better way then? should I have them all have the same class name and then check by class?
jquery_check
@jquery_check I've updated my answer with a slighter more verbose explanation.
Jonathan Sampson
thanks, appreciate the help I have it working with class names now. Thanks again
jquery_check