【发布时间】:2019-06-02 16:04:37
【问题描述】:
有一个包含两个文本字段和一个复选框的表单,它们都是必需的并且具有 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>
【问题讨论】:
-
此表单中不需要复选框。只需将其替换为
By submitting this form I agree with <whatever I should agree>之类的文本即可。 -
@KoshVery——在许多司法管辖区,根据具体情况,复选框是是必需的。
-
@RobG,您能否提供一些相应法律的链接?
-
@KoshVery 这不是某种法律咨询论坛,但在许多情况下,您需要用户的明确同意而不是默示同意。 GDPR 就是一个例子,用户需要明确同意才能收集他们的数据。
-
@KoshVery—我为客户工作过的法律建议说,如果要求消费者同意条款和条件,则需要一个复选框(或类似的 UI 小部件),所以我将它们放入.它们不能被预先选中,用户必须实际选中复选框并选中它。如果您在消费者电子商务网站上工作,您很快就会发现,如果司法管辖区要求(并且 BA 已正确完成他们的工作),这可能是一项明确的要求。如果您想要更多,请寻求自己的建议。
标签: javascript jquery html validation checkbox