JQUERY获取按ID检查的复选框列表

时间:2022-01-10 20:33:24

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:

我目前有一个复选框列表,所有复选框都具有隐藏的相同ID,我想获取已检查的列表,这可能吗?我目前正在使用这种格式:

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

任何人都知道更好的方法这样做或为什么我的版本只返回第一个复选框?谢谢

1 个解决方案

#1


5  

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

您不应该重复使用ID值,它们应该是唯一的:

$("#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.

理想情况下,您应该为它们提供相同的类或名称,具体取决于您希望如何使用它们。但是,您不应该在一个页面上反复使用相同的ID。

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

#1


5  

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

您不应该重复使用ID值,它们应该是唯一的:

$("#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.

理想情况下,您应该为它们提供相同的类或名称,具体取决于您希望如何使用它们。但是,您不应该在一个页面上反复使用相同的ID。

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