0

I have the below code that I took it from w3school, if I didn't type in input it will print an error and it won't send the parameters until I type anything.

what I need to do is I want to separate the javascript code, when I do that it prints the error and move me to PHP page, what should I do to print the error and stop until I type any?

w3school code :

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
  let x = document.forms["myForm"]["fname"].value;
  let error = document.getElementById("error");
  if (x == "") {
    error.innerHTML = "Error";
    return false;
  }
}
</script>
</head>
<body>

<form name="myForm" action="action_page.php" onsubmit="return validateForm()" method="post">
  Name: <input type="text" name="fname">
    <div id="error"></div>
  <input type="submit" value="Submit">
</form>
  
</body>
</html>

My code :

window.addEventListener("load", function() {
    let submitFORM = document.getElementById("form");
    submitFORM.addEventListener("click", validateForm); 

    function validateForm() {
        let x = document.forms["myForm"]["fname"].value;
        let error = document.getElementById("error");
        if (x == "") {
            error.innerHTML = "Error";
            return false;
        }
    }
}); 
<!DOCTYPE html>
<html>
<head>
  <script src="js/js.js"></script>
</head>
<body>

<form name="myForm" action="action_page.php"  method="post">
  Name: <input type="text" name="fname">
    <div id="error"></div>
  <input type="submit" id="form" value="Submit">
</form>
  
</body>
</html>

Thanks in advance

Dany
  • 31
  • 5
  • If I understood correctly, you want to prevent the form being submitted if there's a validation error detected by your JS? – El_Vanja Dec 03 '20 at 21:01
  • Yes, I would to print an error is the input is empty, otherwise it should be submitted – Dany Dec 03 '20 at 21:06
  • Then all you need is to [prevent the default behaviour](https://stackoverflow.com/a/8664535/4205384). And if validation passes, manually trigger the submit event. – El_Vanja Dec 03 '20 at 22:04
  • Could you please help me how to do manually trigger submit event – Dany Dec 03 '20 at 23:11
  • For any JS needs you might have, consult the [MDN page](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit). – El_Vanja Dec 04 '20 at 07:40

0 Answers0