javascript 检查是否选中了具有特定 id 的复选框 JQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31190365/
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
Check if checkbox with specific id is checked JQuery
提问by Anand
Please help me how to identify if a checkbox with specific id is checked/unchecked.
请帮助我如何确定是否选中/取消选中具有特定 ID 的复选框。
<input name="A" id="test" type="checkbox" value="A" />
<input name="B" id="test" type="checkbox" value="B" />
<input name="C" id="test1" type="checkbox" value="C" />
<input name="C" id="test1" type="checkbox" value="D" />
If i check the checkbox with id="test" and name="a", then the event should fire and otherwise it should not for rest of the checkbox with different id other than "test"
如果我用 id="test" 和 name="a" 选中复选框,那么事件应该触发,否则它不应该用于具有除“test”以外的不同 id 的复选框的其余部分
Please help
请帮忙
回答by lshettyl
Element IDs in a given document mustbe unique! Hence, change your HTML to something like below and take a look at the script.
给定文档中的元素 ID必须是唯一的!因此,将您的 HTML 更改为如下所示的内容并查看脚本。
$(function() {
$(":checkbox").on("change", function() {
//When the id is test1
//And name is A
//And it's checked
if (this.id === "test1" && this["name"] === "A" && this.checked) {
alert ("Checkbox with name A and ID test1 is checked");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="A" id="test1" type="checkbox" value="A" />
<input name="B" id="test2" type="checkbox" value="B" />
<input name="C" id="test3" type="checkbox" value="C" />
<input name="C" id="test4" type="checkbox" value="D" />
回答by Federico Massi
Since you tag JQuery you can find it helpful
由于您标记了 JQuery,您会发现它很有帮助
AAA <input type="checkbox" id="test" />
BBB <input type="checkbox" id="test1" />
CCC <input type="checkbox" id="test2" />
and
和
$( "input" ).on( "click", function() {
// for a specific one, but you can add a foreach cycle if you need more
if($('#test').is(":checked")){
alert('is checked!');
}else {
alert('is NOT checked!');
}
});
回答by kavetiraviteja
Id's must be Unique.... otherwise when you use document.getElementById();
Id 必须是唯一的.... 否则当你使用 document.getElementById();
It will select First occurence of specific Id...
它将选择特定 ID 的首次出现...
Instead implement like this..
而是像这样实施..
<input name="A" type="checkbox" value="A" />
<input name="B" type="checkbox" value="B" />
<input name="C" type="checkbox" value="C" />
<input name="C" type="checkbox" value="D" />
and trigger a event on click oncheck box and use document.getElementsByName('');
并在单击复选框时触发事件并使用 document.getElementsByName('');