2

I am trying to follow all the examples out there but I am not having any luck. I created a plunker using a jquery validation check. I need to only allow 1 checkbox selection out of the group. plunker

  <body ng-controller="MainCtrl">
  <div class="form-group fg-line">
    <label for="companies" class="control-label"><b>Role Type</b></label><br /> <br />
 <table>
    <tr ng-repeat="model in userRoles">
      <td>
        <div class="checkbox m-b-15">
          <label>
            <input id="rolebox" class="check" type="checkbox" ng-model="model.RoleId">
            <i class="input-helper"></i>
               {{model.Name}}
         </label>
       </div>
    </td>
 </tr>
   </table>
      </div>    
      <script>
       var checked = [],
          $check = $('.check').change(function () {
            if (this.value == -1 && this.checked) {
                $check.not(this).prop('disabled', true).prop('checked', false);
                checked = [];
            }
            else {
                $check.prop('disabled', false);
                checked.push(this);
                checked = $(checked)
                checked.prop('checked', false).slice(-2).prop('checked', true);
            }
        });

6
  • 3
    Why aren't you just using a radio rather than a check box, as check boxes typically indicate a multi select where as radios are single. Not to derail the question but just a suggestion. Commented Jul 28, 2015 at 12:24
  • good point. didnt think about that Commented Jul 28, 2015 at 12:27
  • Or use if ( $(":checkbox:checked").length > 1 ) { // more than one selected } Commented Jul 28, 2015 at 12:28
  • ca you please show in plunker Commented Jul 28, 2015 at 12:29
  • And you have no jQuery included? Commented Jul 28, 2015 at 12:39

2 Answers 2

3

I need to only allow 1 checkbox selection out of the group.

As mentioned in one of the comments to your question, you should really use radio buttons for this purpose as they are meant for this kind of situation. If you had to use checkboxes, you could do the following.

$(document).on("change", ".check", function() {
    var $allCheckboxes = $(".check");
    $allCheckboxes.prop("disabled", false);
    this.checked && $allCheckboxes.not(this).prop("disabled", true);
});

Your updated plunker

Sign up to request clarification or add additional context in comments.

Comments

2

Assign same name value to all checkboxes. For example:

 <input name="nm" id="rolebox1" class="check" type="checkbox" ng-model="model.RoleId">
 <input name="nm" id="rolebox2" class="check" type="checkbox" ng-model="model.RoleId">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.