jquery_check
jquery_check

Reputation: 33

JQUERY get list of checkboxes that are checked by ID

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

Upvotes: 2

Views: 4281

Answers (1)

Sampson
Sampson

Reputation: 268324

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

Upvotes: 5

Related Questions