显示警报后停止提交

时间:2020-02-27 16:27:19

标签: javascript html

我有一个表单,其中包含文本inputsubmit。如果输入为空,我试图用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>

当我单击submit并且为空时,表单仍然提交并且不显示警报。我将如何阻止它提交而显示警报?

1 个答案:

答案 0 :(得分:2)

运行您的代码时,单击“提交”实际上会收到警报。您确定正确附加了事件处理程序吗?我猜测也许实际上是在显示警报,但无论表单值是否有效,它仍然会提交。

如果要阻止提交表单,请调用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>