Friday, November 13, 2009

Making Checkboxes behave like Radio Buttons using jQuery

Sometimes you might need Checkboxes to behave like Radio Buttons on your webpage because you may only want zero or one selection from a category of choices. You cannot select 0 or 1 choice from a Radio Button Group because Radio Button groups are meant to select only one choice from a group.

I have written an easy to use and understand code in jQuery for achieving this task. In this example, all the checkboxes with name Colors are assigned a click function (Checkbox_to_RadioButton()) when the page loads for the first time. The Checkbox_to_RadioButton() is a generic function which will automatically uncheck all other other checkboxes with the same name/group.

Too make this work on your page, you just need to paste this JavaScript code in the head section of your webpage and set the Checkbox group name in the page ready function.

JavaScript Code:
<script type="text/javascript" src="http://jqueryui.com/latest/jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
      $('input:checkbox[name=Colors]').click(function(){
            Checkbox_to_RadioButton(this);
      });
});
function Checkbox_to_RadioButton(box){
      $('input:checkbox[name=' + box.name + ']').each(function(){
            if (this != box) $(this).attr('checked', false);
      });
}
</script>

HTML Code:
<input type="checkbox" name="Colors" value="Red" />Red<br />
<input type="checkbox" name="Colors" value="Blue" />Blue<br />
<input type="checkbox" name="Colors" value="Green" />Green<br />
<input type="checkbox" name="Colors" value="Yellow" />Yellow<br />

11 comments:

  1. Thanx. I was looking for this. Good work :)

    ReplyDelete
    Replies
    1. Not working , can you tell me what I am doing wrong. I have display tag, records will be loaded dynamically and each record will have check box. I have used same code by replacing the name of the check box. Seriosly looking for this functionality.

      Appreciate your help.

      Delete
  2. Anonymous, looks like you are assigning the click event before all your checkboxes are loaded. Try jQuery Live (http://api.jquery.com/live/) functionality to attach click events.

    ReplyDelete
    Replies
    1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

      Delete
  3. There's nothing wrong with the code. The path of jQuery UI is not found. Instead, change it to --> http://code.jquery.com/jquery-1.8.3.js

    ReplyDelete
  4. Thanks for code. It doesn't work when you have multiple "sets" (or even individual sets) of checkboxes (each having their own 'name'), it simply deselects everything that is not the current checkbox being checked. To make this work within the context of the current "set", the code should change to only disable within the same set/group:

    function DeselectOtherCheckboxes(box) {
    $('input:checkbox[name=' + box.name + ']').each(function () {
    if (this.name === box.name && this !== box) {
    $(this).attr('checked', false);
    }
    });
    }

    ReplyDelete
    Replies
    1. Actually there is no need to narrow down with the IF condition. The problem is actually with the selector itself. It needs quotes to actually filter. I'm using double quotes but it should work with single quotes too (escape it with the slash \ )

      Instead of: $('input:checkbox[name="' + box.name + '"]')
      It should be: $('input:checkbox[name="' + box.name + '"]')

      Delete
  5. mytectra placement Portal is a Web based portal brings Potentials Employers and myTectra Candidates on a common platform for placement assistance.

    ReplyDelete
  6. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

    ReplyDelete

Thanks a lot for your valuable comments :)