有一个表单,其中有两个文本字段和一个复选框,所有这些都是必需的,并且具有 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>
最佳答案
我的做法与 Kubwimana Adrien 的答案非常相似,最初渲染一个禁用的按钮。
此外,一般来说,将验证 bool 值的初始状态设置为 TRUE 并不被认为是安全的。因此,稍微改变一下代码。
const inputSelector = ':input[required]:visible';
function checkForm() {
// here, "this" is an input element
var isValidForm = false;
$(this.form).find(inputSelector).each(function() {
if (((this.type != 'checkbox') && (this.value.trim() != "")) || (this.type == 'checkbox' && this.checked)) {
isValidForm = true;
}
else{
isValidForm = false
return false //break out of each loop
}
});
$(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).on("keyup change", checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<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" disabled>Submit</button>
</form></body>
关于javascript - 如何根据复选框状态禁用/启用提交按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54083739/