-2

I'm trying to have a form where I can search a database, but also have simple error handling where I can check if the user did not enter anything and run the function validateForm. However I'm not sure how to do both.

<form action="http://apsrd7252:5000/result/" method="POST">
  <input type="text" id="IDSub" name="hostname" />
  <input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>

Here's the script

function validateForm() {
  var a = document.getElementById("IDSub");
  if( a.value == null) {
    alert("Please fill in an ID");
    return false;
  } else {
    window.location.href = "http://apsrd7252:5000/result";
  }
}
sheriffderek
  • 8,848
  • 6
  • 43
  • 70

1 Answers1

0

Instead of "null" in if condition simply use empty string like "".

function validateForm() {
  var a = document.getElementById("IDSub");
  if( a.value == "") {
    alert("Please fill in an ID");
    return false;
  } else {
    window.location.href = "http://apsrd7252:5000/result";
  }
}
<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body>
    <form action="http://apsrd7252:5000/result/" method="POST">
  <input type="text" id="IDSub" name="hostname" />
  <input onclick="return validateForm()" type="submit" value="Submit" placeholder="Host Name" />
</form>
  </body>

</html>
Md Junaid Alam
  • 1,131
  • 13
  • 20