jquery:选中并禁用复选框,选中另一个复选框 [英] jquery: check and disable checkbox on checking another checkbox

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

问题描述

我有一些div。每个都包含两个复选框(每个复选框都在同一个类'class3'的div中)。
我想,当用户检查第一个复选框,第二个被选中和禁用。
我尝试过:

I have some divs. Each of them contains two checkbox (each checkbox is in a div of a same class 'class3'). I would that when the user checks the first checkbox, the second one is checked and disabled. I've tried with :

 $('.class1').live('click', function () {
var n = $(this).siblings('input:checkbox');
if ($(this).attr('checked')) {
    n.attr('disabled', true); 
} else {
    n.attr('disabled',false);
} 
return false;
});

这样,两个复选框都被启用,但是当我点击第一个时,没有任何反应。

In this way the two checkbox are enabled, but when I click on the first one, the check doesn't appear and nothing happens.

 <div class="elements">
 <div class="class3">
 <input class="class1" type="checkbox" value="1" name="first" id="first" />
 </div>
 <div class="class3">
 <input class="class2" type="checkbox" value="1" name="second" id="second" />
 </div>
 </div>


推荐答案

的类1:使用类似于:

  $('.class1 input:first-child').live('change', function () {

(我使用了更改而不是点击,因为它更通用。
只添加第一个元素而不是整个div,确保只在需要时作出反应。

(I've used change instead of click because it's a bit more generic. ) Only attaching the first element and not the entire div makes sure you only react when needed.

更多的禁用,因为你使用它应该工作,但兄弟姐妹只有在第一个复选框未嵌套在另一个元素(例如段落)中时才会工作。

Futher the disabling as you have used it should work, but siblings will only work if your first checkbox is not nested inside another element (e.g. a Paragraph)

示例fiddle: http://jsfiddle.net/Zqz63/

编辑
在你更新的帖子中的html,兄弟姐妹将不会工作,你可以查找父母链找到.elements div并向下看看有复选框(除了选择的)

edit Seeing the html in your updated post , siblings will indeed not work, you could look up in the parents chain to find the .elements div and look down for there for checkboxes (other than the selected)

 var n = $(this).parents('.elements').find('input:checkbox').not(this);

jsfiddle没有反应,所以我把示例移动到jsbin: http://jsbin.com/ahemet/3/edit
(NB,在当前jsbin版本中没有仅适当选择第一个复选框,因此事件也将在第二个复选框触发,但我估计这是在您的问题的范围之外)

jsfiddle is unresponsive, so I've moved the sample to jsbin: http://jsbin.com/ahemet/3/edit (NB, in the current jsbin version there is no proper selection of only the first checkbox, so the event will also fire on the 2nd checkbox, but I reckoned that was outside the scope of your question)

edit 2
使用class1始终为第一个复选框,class2始终为第二个的信息:

edit 2 Using the information that class1 is always the first checkbox and class2 always the second:

$('input:checkbox.class1').live('change', function () {

  var n = $(this).parents('.elements').first().find('input:checkbox.class2');

  if ($(this).attr('checked')) {
      n.attr('checked',true);
      n.attr('disabled', true);
  } else {
      n.attr('disabled',false);
  }
});

测试: http://jsbin.com/ahemet/4/edit

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

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