如何只为一个选项添加复选框选择?

时间:2015-10-16 16:49:06

标签: jquery

我在调查中有两种问题。用户可以在每个问题中选择多个选项,然后在用户必须只做出一个选择的其他问题。我不想使用单选按钮。到目前为止,我已经这样做了,但它没有用。

<ol class = "single">
   <li> question: question one</li>
   <li><input type="checkbox"> choice one</li>
   <li><input type="checkbox"> choice two</li>
   <li><input type="checkbox"> choice three</li> 
</ol>

<ol class = "multiple">
   <li> question: question two </li>
   <li><input type="checkbox"> choice one </li>
   <li><input type="checkbox"> choice two </li>
   <li><input type="checkbox"> choice three</li> 
</ol>

我的jQuery代码:

$('.single').each(function(){
  $('input:checkbox').click(function(){
    if ($(this).is(':checked')) {
      $('input:checkbox').not(this).prop('checked', false);
    }
  });
});

1 个答案:

答案 0 :(得分:0)

您不必使用each,只需缩小用于绑定点击事件的选择器的范围:

$('.single').find('input:checkbox').click(function() {
    var $this = $(this);
    $this.closest('.single').find('input:checkbox').not($this).prop('checked', false);
});
相关问题