Fetz Fetz -4 years ago 94
HTML Question

JQUERY make checkbox items disabled when user selects one item in particular

I would like to make all other options be set to DISABLED as user clicks on NESSUNA:

HTML:

<input type="checkbox" value="NESSUNA" name="allergie2[]">
<label for="allergie2"> NESSUNA </label>
<br>
<input type="checkbox" value="cereali con glutine" name="allergie2[]">
<label for="allergie2"> Cereali con glutine </label>
<br>
<input type="checkbox" value="crostacei" name="allergie2[]">
<label for="allergie2">Crostacei </label>
<br>
<input type="checkbox" value="latte e lattosio" name="allergie2[]">
<label for="allergie2">Latte e lattosio </label>
<br>
<input type="checkbox" value="lupini" name="allergie2[]">
<label for="allergie2">Lupini </label>





JQuery part (I was trying with first option):

$(function() {
enable_cb();
$("input:checkbox[name='allergie2[]'][value='NESSUNA").click(enable_cb);
});

function enable_cb() {
if (this.checked) {
$("input:checkbox[name='allergie2[]'][value='cereali con glutine']").attr("disabled", true);
} else {
$("input:checkbox[name='allergie2[]'][value='cereali con glutine']").removeAttr("disabled");
}
}

Answer Source

To achieve this you could put an id on the first checkbox along with a common class on the other to make selecting them easier. Then when the first checbox is changed you can enabled/disable the other ones by their class.

Also note that the for attribute on your <label> elements is incorrect. It should hold the id of the related checkbox, not it's name. Try this:

$('#nessuna').change(function() {
  $('.checkbox').prop({
    checked: false,
    disabled: this.checked
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="NESSUNA" name="allergie2[]" id="nessuna">
<label for="nessuna"> NESSUNA </label><br>

<input type="checkbox" value="cereali con glutine" name="allergie2[]" class="checkbox" id="cereali">
<label for="cereali"> Cereali con glutine </label><br>

<input type="checkbox" value="crostacei" name="allergie2[]" class="checkbox" id="crostacei">
<label for="crostacei">Crostacei </label><br>

<input type="checkbox" value="latte e lattosio" name="allergie2[]" class="checkbox" id="latte">
<label for="latte">Latte e lattosio </label><br>

<input type="checkbox" value="lupini" name="allergie2[]" class="checkbox" id="lupini">
<label for="lupini">Lupini </label>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download