开发者

JQUERY get list of checkboxes that are checked by ID

开发者 https://www.devze.com 2022-12-18 13:41 出处:网络
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:

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 wh开发者_如何学编程y my version is only returning the first checkbox? Thanks


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号