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