How can I not select other checkboxes when selecting a checkbox? [duplicate]

2

I have these 3 checkboxes

<td style="background-color: #D6FAFA"><input type="checkbox" name="box2" id="ok" /></td>
<td style="background-color: #D6FAFA"><input type="checkbox" name="box2" id="nok"/></td>
<td style="background-color: #D6FAFA"><input type="checkbox" name="box2" id="na"/></td>

When checking a checkbox with id = ok I can not mark the other two checkboxes and do the same thing with the other checkboxes, ie I'll only be able to check if I have everything unchecked if one of them has checked the others lock

I tried this did not work out

$(function() {
  enable_cb();
  $("#ok").click(enable_cb);
  $("#nok").click(enable_cb);
  $("#na").click(enable_cb);
});

function enable_cb() {
  if (this.checked) {
    $("#nok").attr("disabled",true);
    $("#na").attr("disabled",true);
  } else {
     $("#nok").removeAttr("disabled");    
     $("#na").removeAttr("disabled");
  }
}   

Can anyone tell me what's wrong, I'm using the jquery.v1.9.1 library.

    
asked by anonymous 21.07.2016 / 17:10

2 answers

4

You could put a class to group these checkboxes that you want to work from, so it would look like this:

    $(function(){
       $('input.checkgroup').click(function(){
          if($(this).is(":checked")){
             $('input.checkgroup').attr('disabled',true);
             $(this).removeAttr('disabled');
          }else{
             $('input.checkgroup').removeAttr('disabled');
          }
       })
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script><inputtype="checkbox" class="checkgroup" id="ok"/>
    <input type="checkbox" class="checkgroup" id="nok"/>
    <input type="checkbox" class="checkgroup" id="na"/>

Fiddle: here

    
21.07.2016 / 17:25
4

Semantically the most correct is to use input type="radio" . This type of input chooses only one, the rule is that everyone must have the same name . The only thing this type does not allow is uncheck all.

If you need this functionality you can use it with type="checkbox" :

var inputs = $('[type="checkbox"]'); // colocar os inputs em cache
inputs.on('click', function() { // juntar auscultador de evento
    inputs.get().forEach(function(el) { // iterar com a array nativa
        el.checked = el == this && this.checked; // marcar ou desmarcar o elemento iterado
    }, this);
});

jsFiddle: link

    
22.07.2016 / 00:08