This is my HTML and JS code:
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
function validateForm() {
let x = document.forms[myForm][lname].value;
if (x == "") {
alert("Last name should be filled out");
return false;
}
else
alert("Thank you for your response");
}
</script>
</head>
<body>
<h1>Student Information Form</h1>
<br>
<br>
<form name="myForm" onsubmit="return validateForm()" method="post">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="fname"><br> <br>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<input type="reset">
<input type="submit" value="Submit">
</form>
</body>
</html>
And upon clicking the submit button I’m calling the alert to appear but it’s not appearing. When I have data in the input tags, when I click submit the data just dissapears. Why is this happening???
3
Answers
There are 2 problems with your code:
the first instance of
validateForm()
is over written by the second and will never be called. You should move all your code into a single function.You are missing quotes around the strings in the
document.forms["myForm"]["lname"].value
code.as Allen Morris said, you have multiple things todo:
validateForm()
function it’s overwritten by the second one, so you have to merge your both functions in one.document.forms["myForm"]["lname"]
so after we fix this errors and merge our logic in one, your function will looks like:
Here is a working snippet of your code.
The function
validateForm()
which you used twice is the problem that you are facing. If you have to use a function, you should just invoke it once.For validating the rest of the inputs, I added a bit more logic to the rest of the function in case you would have to validate your last name.
Hope that helps.