jQuery复选框值,以逗号分隔列表 [英] jQuery checkbox values to comma separated list
问题描述
我有几个带有名称数组的复选框,并且我希望复选框的输出是一个带有逗号分隔列表的变量.
I have several checkboxes with a name array and I want the output of the checked boxes to be a variable with a comma separated list.
<input type="checkbox" name="example[]" value="288" />
<input type="checkbox" name="example[]" value="289" />
<input type="checkbox" name="example[]" value="290" />
例如,如果选择第一个和最后一个框,则输出为:
For example if the first and last box are selected the output will be:
var output = "288,290";
我该如何使用jQuery?
How can I do this with jQuery?
推荐答案
您可以使用:checkbox
和名称属性选择器(:checkbox[name=example\\[\\]]
)来获取具有name="example[]"
的复选框列表,然后可以使用:checked
过滤以仅获取选中的复选框.
You can use :checkbox
and name attribute selector (:checkbox[name=example\\[\\]]
) to get the list of checkbox with name="example[]"
and then you can use :checked
filter to get only the selected checkbox.
然后,您可以使用.map
函数从选定的复选框中创建一个数组.
Then you can use .map
function to create an array out of the selected checkbox.
var output = $.map($(':checkbox[name=example\\[\\]]:checked'), function(n, i){
return n.value;
}).join(',');
这篇关于jQuery复选框值,以逗号分隔列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!