This tutorial shows you how to make Checkboxes act like radio buttons, this really need when the designer designed a quiz page with checkboxes instead of radio buttons and the client wants only in that way. Sad isn’t it?
But don’t worry here is the solution for that, you can see the Demo and Download the script at the bottom of this post if you wish.
jQuery Part:
1 2 3 4 5 |
$("input:checkbox").click(function(){ var checkboxgroup = "input:checkbox[name='"+$(this).attr("name")+"']"; $(checkboxgroup).attr("checked",false); $(this).attr("checked",true); }); |
Here is the demo code to play around with it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<html> <head> <title>Checkboxes Behave like Radio Buttons using jQuery - Tutorialsmade.com</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> <script> $(function(){ $("input:checkbox").click(function(){ var checkboxgroup = "input:checkbox[name='"+$(this).attr("name")+"']"; $(checkboxgroup).attr("checked",false); $(this).attr("checked",true); }); }); </script> </head> <body> <h1>Checkboxes Behave like Radio Buttons using jQuery - Tutorialsmade.com</h1> <p>Question 1:</p> <input type="checkbox" name="g1" value="ans1"/>Ans1 <br /> <input type="checkbox" name="g1" value="ans2"/>Ans2 <br /> <input type="checkbox" name="g1" value="ans3"/>Ans3 <br /> <hr /> <p>Question 2:</p> <input type="checkbox" name="g2" value="ans1"/>Ans1 <br /> <input type="checkbox" name="g2" value="ans2"/>Ans2 <br /> <input type="checkbox" name="g2" value="ans3"/>Ans3 <br /> </body> </html> |
Check out the demo and download too.
your code is wrong the checkbox is not working like radio button
Hi, it was not working because the jQuery was not loaded. Please check the demo now it’s working. You could’ve tested it simply by copy-pasting the entire code and save it as an HTML file in your local.
you have to use .prop instead of .attr
$(function(){
$(“input:checkbox”).click(function(){
var checkboxgroup = “input:checkbox[name='”+$(this).attr(“name”)+”‘]”;
$(checkboxgroup).prop (“checked”,false);
$(this).prop (“checked”,true);
});
});