我有一个表单,要求用户单击复选框才能提交。在提交时,如果用户未选中该框,我会显示一条错误消息。目前,如果我继续单击,消息就会不断添加。我如何更改它,使其只显示一次。
onFormSubmit : function(isFormValid, event){
if ($('#agree_to_terms_join').prop('checked')) {
$('#agree_to_terms_label').parent().removeClass('has-error').find('.error').remove();
} else {
$('#agree_to_terms_label').parent().addClass('has-error').append(
'<div class="textbox-alert help-block error" style="display: block;">' +
'<div class="type" style="display: block;">Message goes here</div>' +
'</div>'
);
return false;
}
}
最佳答案
虽然此解决方案可能需要额外的工作并更改一些 html,但这是更好的方法:
- 将 html block 保留在表单本身中
- 并使用 CSS 根据错误切换可见性。
JS
onFormSubmit: function(isFormValid, event) {
var elem = $('#agree_to_terms_label');
elem.is(":checked") ? elem.parent().removeClass("error"):elem.parent().addClass("error");
}
CSS:
.has-error .error {
display: block;
}
.error {
display: none;
}
HTML
<div class="textbox-alert help-block error">
<div class="type" style="display: block;">Message goes here</div>
</div>
您可以将此 HTML 保留在表单本身中。切换类比更改 DOM 更快
关于javascript - 表单提交上的复选框 : error keeps displaying on button click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39294875/