javascript - 如何根据复选框状态禁用/启用提交按钮?
问题描述
有一个带有两个文本字段和一个复选框的表单,它们都是必需的并且具有 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>
解决方案
仅需要 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>
推荐阅读
- asp.net-core - 如何在 RouteEndpoint 中使用 RequestDelegate 调用控制器和操作
- forms - Xamarim 表单文档扫描仪
- python - df 多列的加权平均聚合
- javascript - html2canvas 给出空白图像
- ios - 卸载后清除我的 OS X 应用程序的用户默认设置
- node.js - bash 中的 Node.js 主要版本
- windows - 在 docker 桌面 (docker-compose) 上,是否可以在 bash 模式下直接在 PHP 容器上打开 CLI?
- java - 动态 Web 项目通过 Servlet 获取完整路径
- axapta - 覆盖 displayOption 以根据 displayMethod 中的值为某些行着色
- xml - 通过更改 xml 文件改进 opencv 人脸检测