首页 > 解决方案 > 如何根据复选框状态禁用/启用提交按钮?

问题描述

有一个带有两个文本字段和一个复选框的表单,它们都是必需的并且具有 required 属性。

只有在填写并检查了所需的输入时,才应启用提交按钮。

使用当前代码,文本字段验证似乎工作正常,但它对复选框没有影响。

提琴手

<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>

<script>
    const inputSelector = ':input[required]:visible';

    function checkForm() {
        // here, "this" is an input element
        var isValidForm = true;
        $(this.form).find(inputSelector).each(function() {
            if (!this.value.trim()) {
                isValidForm = false;
            }
        });
        $(this.form).find('.monitored-btn').prop('disabled', !isValidForm);
        return isValidForm;
    }
    $('.monitored-btn').closest('form')
        // in a user hacked to remove "disabled" attribute, also monitor the submit event
        .submit(function() {
            // launch checkForm for the first encountered input,
            // use its return value to prevent default if form is not valid
            return checkForm.apply($(this).find(':input')[0]);
        })
        .find(inputSelector).keyup(checkForm).keyup();
</script>

标签: javascriptjqueryhtmlvalidationcheckbox

解决方案


仅需要 CSS

#otherForm-submitBtn {
  enabled: false;
  color: grey;
}

input[type='checkbox']:checked ~ #otherForm-submitBtn {
  enabled: true;
  color: black;
}
<form action="#otherForm">
   Name * <input name="otherForm-name1" placeholder="required" required> <br />
   Tel * <input name="otherForm-surname" placeholder="required" required> <br />
   <input type="checkbox" name="otherForm-chcekbox" required><label for="otherForm-chcekbox">I agree</label> <br />
   <button id="otherForm-submitBtn" class="monitored-btn" type="submit">Submit</button>
</form>


推荐阅读