Quazey
Quazey

Reputation: 81

Stopping submitting when alert is shown

I have form that has text input and submit. I'm trying to show an alert with Javascript if input is empty.

This is my code:

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>

When I click submit and it is empty, form still submits and doesn't show the alert. How would I prevent it from submitting and instead show an alert?

Upvotes: 0

Views: 1097

Answers (1)

QuinnF
QuinnF

Reputation: 2169

When I run your code, I actually do get alerts when I click "submit". Are you sure you are attaching the event handler correctly? I'm guessing maybe what's actually happening is that the alert is showing but then it submits anyway no matter if the form value is valid.

If you want to prevent the form from submitting, call e.preventDefault() where e is the event object which will be passed as the first argument to your handler function.

Here is an example codepen: 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>

Upvotes: 2

Related Questions