javascript - 阻止 btn,直到至少选中一个偏移量的 1 个复选框

标签 javascript jquery twitter-bootstrap

这里有点沮丧,无论如何我都无法完成这项工作。我有一个带有 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);

Here is the example


快速建议:如果您有独特的元素,请考虑为它们使用 id 属性。例如:

<button id="btn6" ...>

使用以下 JQuery 选择器:

$("#btn6")...

关于javascript - 阻止 btn,直到至少选中一个偏移量的 1 个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22177359/

相关文章:

javascript - 为什么我收到 "Uncaught ReferenceError: userId is not defined"错误?

css - 在导航栏之前的顶部显示 Bootstrap 横幅

html - 如何使用 bootstrap 3 使链接和按钮在列表中对齐

css - Bootstrap : How to align Image tag and two <p> tags in a bootstrap div?

javascript - 如何将所有图层 Canvas 居中?

javascript - 为什么 javascript "for loop"对不同类型的对象有不同的行为

javascript - 如何使用 jQuery 获取元素的文本兄弟?

javascript - 如何使用 jquery 删除字段?

javascript - 尝试导入类时出现意外的标识符 {classname}

javascript - 将对象返回给 Controller 并使用 AngularJS 打印属性值