0

I'm submitting a form with input text to my server through my web client. What I'm trying to do is to check whether the user has passed in text into the input field before sending the form by hitting the submit button.

What I have tried so far:

var form = document.getElementById("id");

document.getElementById("id").addEventListener("click", function() {
  var input = document.getElementById("content").value;
  if (input == "") {
    alert("write something in the textfield");
  } else {
    form.submit();
  }
});
<form action="" method="post" id="id">
  <input type="text" name="name" id="content">
  <button type="submit" id="submit-id">submit text</button>
</form>

Any good tips on how to do this?

3 Answers 3

2

You want preventDefault on the submit event

document.getElementById("id").addEventListener("submit", function(e) {
  const input = document.getElementById("content").value;
  if (input.trim() === "") {
    alert("write something in the textfield");
    e.preventDefault()
  }
});
<form action="" method="post" id="id">
  <input type="text" name="name" id="content">
  <button type="submit" id="submit-id">submit text</button>
</form>

Alternatively just add required attribute - no need for script:

<form action="" method="post" id="id">
  <input type="text" name="name" id="content" required>
  <button type="submit" id="submit-id">submit text</button>
</form>

Sign up to request clarification or add additional context in comments.

Comments

0

you can use the simple code snippet instead :

    <form action="" method="post" id="id">
      <input type="text" name="name" id="content" required>
      <button type="submit" id="submit-id">submit text</button>
    </form>

Comments

0

function submitIt(e) {
  var formData = new FormData(e);
  var object = {};
  formData.forEach(function(value, key) {
    object[key] = value;
  });
  if (object.name == "") {
    alert("null");
  } else {
    alert("ok");
    return true;
  }
  return false;
}
<form onsubmit="return submitIt(this)">
  <input type="text" name="name">
  <button>submit text</button>
</form>

1 Comment

Code would still submit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.