我的表单包含文本输入
和提交
。如果输入为空,我尝试用 Javascript 显示警报。
这是我的代码:
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, "");
}
function emptyArea() {
if (document.getElementById("type-text").value.trim() == '') {
alert("Please fill all fields");
} else("OK");
}
<form>
<input id="type-text" type="text" placeholder="Type some text">
<input type="submit" placeholder="Submit" onclick="emptyArea()">
</form>
当我点击提交
并且它是空的时,表单仍然提交并且不显示警报。我如何阻止它提交并显示警报?
最佳答案
当我运行您的代码时,当我单击“提交”时,我实际上确实收到了警报。您确定正确附加了事件处理程序吗?我猜测可能实际发生的情况是警报正在显示,但无论表单值是否有效,它都会提交。
如果您想阻止表单提交,请调用e.preventDefault()
其中 e
是事件对象,它将作为第一个参数传递给处理函数。
这是一个示例代码笔: https://codepen.io/quinnfreedman/pen/PoqmGYb
function emptyArea(e) {
if (document.getElementById("text").value.trim() == '') { // .trim is supported by browsers since IE9
alert("Please fill all fields");
// the conditions were not met, so call preventDefault to
// stop the browsers default behavior of submitting the form
e.preventDefault();
e.stopPropagation();
} else {
// If we don't preventDefault, the form will submit after this alert
alert("OK")
}
}
document.getElementById("Submit").addEventListener("click", emptyArea)
<form action="#">
<input type="text" id="text" />
<input type="submit" id="Submit" />
<!-- NEVER call anything "submit" in a form -->
</form>
关于javascript - 显示警报时停止提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60437674/