如果选中另一个复选框,则选中复选框 [英] check checkbox if another checkbox is checked
本文介绍了如果选中另一个复选框,则选中复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果选中值为 1 的复选框,我希望自动选中值为 2 的复选框.两者都有相同的 ID,所以我不能使用 getElementById.
I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
我累了:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
推荐答案
您需要将 HTML 和 jQuery 更改为:
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id
是唯一的,你应该使用 class.
id
is unique, you should use class instead.
您的 chk1
和 chk2
选择器有误,请像上面一样使用 '
正确连接.
Your selector for chk1
and chk2
is wrong, concatenate it properly using '
like above.
使用change() 函数检测何时第一次复选框选中或取消选中,然后使用 prop().
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
这篇关于如果选中另一个复选框,则选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文