Making Checkboxes Behave like Radio Buttons

A while back I found the need to have HTML checkboxes behave like radio buttons. As you probably know, the main difference between the two is that multiple checkboxes can be selected at the same time whereas only one radio button can be selected at any given time (of course this changes depending on the context).

So how do you make checkboxes behave like radio buttons? With a bit of Javascript, it's pretty easy (click "Result" to see it in action):

As you can see, only one checkbox can be selected at a time; the checkboxes are behaving like radio buttons! This solution allows you to leave both boxes unchecked, or check only one.

Write a Comment

Comment

32 Comments

  1. cool! May have to use this on a website.

    Also, I started playing with the boxes before reading the post. doh!

    • You’re correct, Raja. The method I described would require you to add additional Javascript code to uncheck all other check boxes. If I was going to use more than one checkbox, I’d probably write a function that searches for checkboxes containing a particular id tag and then unchecks them. That way the code could be changed to if(this.checked) {uncheck_others();}

  2. This is the best solution I have found for this.

    So many other overly complicated efforts to do this same thing.

    Elegant, effective and yet simple.

    Excellent and thanks for posting it !!!

  3. FANTASTICO!!.. I’ve been looking for this script a week ago.. finally found this!!.. thanks for posting

  4. Hi good one Ram i would like to hide some controls with the same functionality how can i means if first check box is checked i would like to show some controls and on checking 2nd i would like to unchecked first which works but at the same time i would like to make the visibility of control to false can you help me

  5. Hi
    I want to use this checkbox in Gridview
    I copied ur code but it is not working can you please tell me how to use in the girdview

  6. plz i want the code for more than 1 checkbox say around 10, if one clicked others should disable and unchecked it shud be enabled….plz help…….if can send the code to my mail

    • Hi Gillian,

      Thanks for letting me know. It looks like an update broke the code that I had on that page. I’ve updated it in the post and have tested it on my iPad with Safari to confirm that it’s working as expected. I hope this helps!

  7. What if its name attribute in array format? for example like this

    name=”food_habits[great_sweet_need][]”