Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select only one checkbox out of three with same name

Tags:

html

jquery

UPDATE:

My code now is something like this: (works).

   $(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" />

I have a questionnaire type form with three checkboxes for each question and I want the user to be able to select only one out of the three.

My HTML is something like this:

Question 1:

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

Question 2:

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

But this allows the user to select all checkboxes for a particular question. And I want it to be able to select only one out of the three. Is there a solution to this?

Thanks

like image 454
Alex Zahir Avatar asked Nov 27 '22 14:11

Alex Zahir


1 Answers

Demo here

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

As per the comment, I assume user must be able to select one out of first three and 1 out of second three checkboxes. Because name attributes are different. Here is demo.

 $("input:checkbox").change(function(){
 var group = ":checkbox[name='"+ $(this).attr("name") + "']";
   if($(this).is(':checked')){
     $(group).not($(this)).attr("checked",false);
   }
 });
like image 64
Exception Avatar answered Dec 09 '22 18:12

Exception