使用 Jquery 选择所有具有相似 ID 的复选框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4894942/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select all checked checkboxes with similar id's using Jquery?
提问by Jishnu A P
This might be the easiest question of the day.
这可能是今天最简单的问题。
i have a groups of checkboxes with similar id's (all starting with someid_
like someid_0
,someid_1
..)
我有一组具有相似 id 的复选框(都以someid_
like someid_0
, someid_1
..开头)
i want to get all checked
checkboxes.
我想获得所有checked
复选框。
I have tried $('input:checkbox[id^="someid_"]:checked')
but it's not working?
我试过了,$('input:checkbox[id^="someid_"]:checked')
但它不起作用?
回答by Harish
this code is working check demo
此代码正在运行检查演示
Markup
标记
<input type="checkbox" id="someid_1" checked/>
<input type="checkbox" id="someid_2" checked/>
<input type="checkbox" id="someid_3" checked/>
<input type="checkbox" id="someid_4"/>
jQuery
jQuery
var n = $('input:checkbox[id^="someid_"]:checked').length;
alert(n); // count of checked checkboxes
$('input:checkbox[id^="someid_"]:checked').each(function(){
alert($(this).attr("id"));});
回答by Niraj Kumar
<head>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
var isChecked = false;
function allSelected()
{
// this line is for toggle the check
isChecked = !isChecked;
//below line refers to 'jpCheckbox' class
$('input:checkbox.jpCheckbox').attr('checked',isChecked);
//OR,
//$('input:checkbox.jpCheckbox').attr('checked','checked');
}
</script>
</head>
<body>
<form>
Select All<input type="checkbox" id="selectAllCheckbox" onclick="allSelected()" /><br/>
A<input type="checkbox" id="jpCheckbox" class="jpCheckbox" /><br/>
B<input type="checkbox" id="jpCheckbox" class="jpCheckbox" /><br/>
C<input type="checkbox" id="jpCheckbox" class="jpCheckbox" /><br/>
</form>
</body>
回答by Prakash
the code you tried is absolutely correct, may b the code ran before parsing the required elements so try,
您尝试的代码是绝对正确的,可能是在解析所需元素之前运行了代码,所以请尝试,
$(document).ready(function(){$('input:checkbox[id^="someid_"]:checked')})
回答by Arun
I'm not sure if you can do a search on the ID attribute. it usually returns only one value. You can set the class to some_0 instead and then search or use a custom attribute like
我不确定您是否可以对 ID 属性进行搜索。它通常只返回一个值。您可以将类设置为 some_0 ,然后搜索或使用自定义属性,如
<input type=checkbox customattr=some_1>
回答by Vivek
try this...
尝试这个...
$('input:checkbox').filter('#someid').attr(":checked")