这里有点沮丧,无论如何我都无法完成这项工作。我有一个带有 2 个偏移量的小表单,每个偏移量包含几个复选框,如下所示:
<input type="checkbox" id="test1" /><label for="test1">
我需要确保用户在每个偏移量中至少选择其中一个以便能够单击此按钮,否则它应该是不可单击 :)
<div class="offset6">
<a class="btn btn-warning" href="#openModal">CONTINUAR<span class="btn_caret"></a>
</span></button>
</div>
最佳答案
这应该适合你:
//listen for changes to any checkbox so we can re-evaluate the button state
$("input[type='checkbox']").change(function(){
validateInput();
});
//checks to see if the button should be enabled or not
function validateInput(){
//get the count of checked items in each of the offsets
var offset3Count = $(".offset3").find("input[type='checkbox']:checked").length;
var offset8Count = $(".offset8").find("input[type='checkbox']:checked").length;
//set the disabled state of the button based on the offset counts
$(".btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
}
//call the function on page load to ensure the button is initially disabled
validateInput();
Here is a working example (我不得不稍微更改您的 HTML,因为它无效)
如果您需要特定的 .btn
,如 offset6
中的那个,请改用此行:
$(".offset6 .btn").prop("disabled", offset3Count == 0 || offset8Count == 0);
快速建议:如果您有独特的元素,请考虑为它们使用 id
属性。例如:
<button id="btn6" ...>
使用以下 JQuery 选择器:
$("#btn6")...
关于javascript - 阻止 btn,直到至少选中一个偏移量的 1 个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177359/