Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: make checkboxes act like radio buttons?

Is there a way to make checkboxes act like radio buttons? I assume this could be done with jQuery?

<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />
<input type="checkbox" class="radio" value="1" name="fooby[1][]" />

<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />
<input type="checkbox" class="radio" value="1" name="fooby[2][]" />

If one box was checked the others in the group would uncheck.

like image 215
superUntitled Avatar asked Jan 15 '11 04:01

superUntitled


People also ask

How can I make a checkbox behave like a radio button in jQuery?

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

How can I make a checkbox work like a radio button?

To make checkbox behave like radio buttons with JavaScript, we can listen to the body element's click listener. And in the listener, we uncheck all the checkboxes and the check off the one that matches the one that's clicked. to add the checkboxes.

Can we use checkbox as radio button?

Both are commonly used together on forms to select options from a list. However, a radio button is a circle with a dot inside, while a checkbox is a square with a checkmark inside—two different visual cues. Some might say that their functions are different, so they should look different.


1 Answers

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

This will do it, although i do agree this might be a bad idea.

Online example: http://jsfiddle.net/m5EuS/1/

UPDATE added group separation.

like image 90
amosrivera Avatar answered Oct 31 '22 17:10

amosrivera