如果选中另一个复选框,请选中复选框 [英] check checkbox if another checkbox is checked

查看:152
本文介绍了如果选中另一个复选框,请选中复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要选中值为2的复选框,以便自动选中值为1的复选框。两者都具有相同的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


$ b b

我累了:

I tired:

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




  1. id

  1. 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().

小提示演示

Fiddle Demo

这篇关于如果选中另一个复选框,请选中复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆