Skindeep2366
Skindeep2366

Reputation: 1559

Javascript to uncheck a checkbox when another is checked

This is a MVC 3 application that uses the razor view engine. I have the following line of code in a view that displays 2 checkboxes. When one is checked the other checkbox should uncheck. I have searched around and between my lack of exp with javascript and the lack of threads found on google related to this i am at a lost for even a code snip of javascript to use for a worthwhile starting point. Any ideas?? This below is what I have coded up on my own but am more stuck than anything with this.

        $("#isStaffCheckBox").change(
              function (e) {
                  var checked = $(this).attr('checked');
                  if(checked)
                  {

    <li>Staff Member: @Html.CheckBoxFor(Function(f) f.isStaff, New With {.id = "isStaffCheckBox"}) Board Member: @Html.CheckBoxFor(Function(f) f.boardMember, New With {.id = "isBoardCheckBox"})</li>

Any help is greatly appreciated..

Upvotes: 4

Views: 7215

Answers (3)

F&#225;bio
F&#225;bio

Reputation: 115

Change the property "("#isBoardCheckBox").prop" to "("#isBoardCheckBox").attr".

Works fine!

  $("#isStaffCheckBox").change(
  function (e) {
      $("#isBoardCheckBox").attr("checked", !this.checked);
  })

Upvotes: 2

Vignesh
Vignesh

Reputation: 1518

// If you use jquery version 1.6.4 or below use "attr", if you use higher versions (1.9 or above) use "prop" instead of attr.

Code:

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Checkbox</title>
        <script type="text/javascript" src="js/jquery-1.6.4.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $(":checkbox").change(function () {
                    $("input:checkbox").attr("checked", false);
                    $(this).attr("checked", "checked");
                });
            });
        </script>
    </head>
    <body>
        <input type="checkbox" id="chk1" value="1" /> Staff Member  <br/>
        <input type ="checkbox" id="chk2" value="2" /> Board Member
    </body>
</html>

Please have a look on this link JsFiddle my code

Upvotes: 0

HMR
HMR

Reputation: 39320

If there is some reason for this to be a checkbox instead of a radio button then the following code should do it.

    $("#isStaffCheckBox").change(
          function (e) {
              $("#isBoardCheckBox").prop('checked',!this.checked);
          }
    });

Upvotes: 5

Related Questions