powered by myself

Mutually exclusive checkboxes with jQuery

I was needing a way for the user to select none or just one item in a set… here is how I’ve managed to achieve this functionality using jQuery:

<html>
  <head>
      <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
      <script type="text/javascript" language="javascript">
          $(document).ready(function() {
              $('.mutuallyexclusive').click(function () {
                  checkedState = $(this).attr('checked');
                  $('.mutuallyexclusive:checked').each(function () {
                      $(this).attr('checked', false);
                  });
                  $(this).attr('checked', checkedState);
              });
          });
      </script>
  </head>
  <body>
      <div>
          Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="mutuallyexclusive">
          Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="mutuallyexclusive">
          Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="mutuallyexclusive">
      </div>
  </body>
</html>

(Based on this post. Thanks Tony.)


Kick It on DotNetKicks.com

3 Comments to Mutually exclusive checkboxes with jQuery

  1. Alex's Gravatar Alex
    October 9, 2008 at 9:24 pm | Permalink

    Thanks, this was really helpful.

  2. Rejish Khan M's Gravatar Rejish Khan M
    September 26, 2009 at 1:54 pm | Permalink

    Thansk for the excellent solution. Since ASP.NET puts a span tag around CheckBox and applies the class to that span, i'd to slightly modify the code as below:

    $(document).ready(function() {
    $('.mutuallyexclusive input').click(function () {
    checkedState = $(this).attr('checked');
    $('.mutuallyexclusive input:checked').each(function () {
    $(this).attr('checked', false);
    });
    $(this).attr('checked', checkedState);
    });
    });

  3. Germán Schuager's Gravatar Germán Schuager
    September 26, 2009 at 2:00 pm | Permalink

    You are welcome.
    That's one good thing about MVC compared to WebForms…. I get to choose my markup and not ASP.NET :)

Keep in touch

Categories