我想在用户点击NESSUNA时将所有其他选项设置为DISABLED:
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部分(我尝试使用第一个选项):
$(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");
}
}
答案 0 :(得分:3)
要实现这一目标,您可以在第一个复选框上放置id
,在另一个复选框上放置一个公共类,以便更轻松地选择它们。然后当第一个checbox被更改时,您可以通过他们的类启用/禁用其他checbox。
另请注意,for
元素的<label>
属性不正确。它应该包含相关复选框的id
,而不是name
。试试这个:
$('#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>
答案 1 :(得分:0)
将class
添加到checkbox
:
<input type="checkbox" value="NESSUNA" name="allergie2[]">
<label for="allergie2"> NESSUNA </label>
<br>
<input type="checkbox" class="disable-others" 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>
并添加处理程序:
$(function() {
$(".disable-others").click(function() {
var current = $(this);
current.prop("checked") ? current.siblings("checkbox").attr("disabled", true) : current.siblings("checkbox").removeAttr("disabled");
});
});