只选择三个具有相同名称的复选框

时间:2013-02-17 04:34:14

标签: jquery html

更新:

我的代码现在是这样的:(有效)。

   $(document).ready(function(){
         $("input:checkbox").click(function(){
var group = "input:checkbox[name='"+$(this).attr("name")+"']";
$(group).attr("checked",false);
$(this).attr("checked",true);
 });


          });   

HTML:

     <input type="checkbox" name="swimming" class="chb" />
     <input type="checkbox" name="swimming" class="chb" />
     <input type="checkbox" name="swimming" class="chb" />

我有一个问卷类型表格,每个问题有三个复选框,我希望用户只能选择三个中的一个。

我的HTML是这样的:

问题1:

             <input type="checkbox" name="ballet" />
             <input type="checkbox" name="ballet" />
             <input type="checkbox" name="ballet" />

问题2:

             <input type="checkbox" name="swimming" />
             <input type="checkbox" name="swimming" />
             <input type="checkbox" name="swimming" />

但是这允许用户选择特定问题的所有复选框。我希望它能够只选择三个中的一个。有解决方案吗?

由于

5 个答案:

答案 0 :(得分:14)

Demo此处

$(':checkbox').on('change',function(){
 var th = $(this), name = th.attr('name'); 
 if(th.is(':checked')){
     $(':checkbox[name="'  + name + '"]').not(th).prop('checked',false);   
  }
});

根据评论,我假设用户必须能够选择前三个中的一个和后三个中的一个复选框。因为名称属性不同。 Here是演示。

 $("input:checkbox").change(function(){
 var group = ":checkbox[name='"+ $(this).attr("name") + "']";
   if($(this).is(':checked')){
     $(group).not($(this)).attr("checked",false);
   }
 });

答案 1 :(得分:7)

您可以尝试使用div。

 <div id="checkboxGroup">
<input type="checkbox" name="ballet" />
<input type="checkbox" name="ballet" />
<input type="checkbox" name="ballet" />
</div>

$('#checkboxGroup input[type=checkbox]').change(function() {
if (this.checked) {
    $('#checkboxGroup input[type=checkbox]').not(
                        $(this)).prop('checked', false);
    }
});

请参阅fiddle

答案 2 :(得分:3)

单选按钮是要走的路。如果需要,您还可以通过在该输入标记中添加“已检查”一词作为属性来预选其中一个选项。

<input type="radio" name="ballet" value="1" checked />
<input type="radio" name="ballet" value="2" />
<input type="radio" name="ballet" value="3" />

答案 3 :(得分:2)

这称为HTML单选按钮。单选按钮组合在一起,单选按钮的概念是组中一次只能选择一个。

名称属性是单选按钮组的名称。

<input type="radio" name="ballet" value="1" />
<input type="radio" name="ballet" value="2" />
<input type="radio" name="ballet" value="3" />

带有单选按钮等组的复选框

请注意,“x”是类,但“name”属性就是您想要的组。

$(".x").click( function() {
    var n = $(this).attr('name');
    $("[name=" + n + ']').prop("checked", false);
    $(this).prop("checked", true);
});

<input type="checkbox" name="swimming" class="x" />
             <input type="checkbox" name="swimming" class="x" />
             <input type="checkbox" name="swimming" class="x" />

<br/>

<input type="checkbox" name="diving" class="x" />
             <input type="checkbox" name="diving" class="x" />
             <input type="checkbox" name="diving" class="x" />

答案 4 :(得分:0)

对于复选框:

$("input:checkbox").click(function () {
    $("[name="+$(this).prop('name')+"]").prop("checked", false);
    $(this).prop("checked", true);
});

您可以改用无线电。

Fiddle For Checkboxes

相关问题