Reputation: 133
I have a problem.
Can you guys help me to see what wrong with the code because even when I click submit without filling the input text box, nothing happens (there is no alert show up)?
I put the index.html file and javascript file in the same folder, I think there is no problem with the path but I don't know why the doesn't run. Inside the console shows up
"Uncaught TypeError: Cannot read property 'firstName' of undefined at script.js:1"
var getInput=document.forms["signup"]["firstName"];
function check(){
if(getInput.value == ""){
window.alert("Please enter a first name");
getInput.focus();
return false;
}
return true;
}
window.onload=check;
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sign up</title>
<script src="./javascript/script.js"></script>
</head>
<body>
<form name="signup" action="#" method="post" onsubmit="return check()">
<label for="inputFirstName">First name</label>
<input type="text" id="inputFirstName" value="" name="firstName">
<input type="submit" value="Click Me">
</form>
</body>
</html>
Upvotes: 0
Views: 1632
Reputation: 22265
this will work fine:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign up</title>
</head>
<body>
<form name="signup" action="#" method="post" >
<label for="inputFirstName">First name</label>
<input type="text" id="inputFirstName" value="" name="firstName">
<button type="submit">Click Me</button>
</form>
<script>
const SignUpForm = document.forms["signup"]
;
SignUpForm.onsubmit = e =>
{
if (!SignUpForm.firstName.value.trim())
{
window.alert("Please enter a first name");
getInput.focus();
e.preventDefault()
}
}
</script>
</body>
</html>
Upvotes: 1
Reputation: 21
Mister Jojo is right! You are having that error because the DOM is not fully loaded before making the check. However, this little alternative code can save you the stress unless you have a purpose why you really want to use your Method.
function check(){
var getInput = document.getElementById("inputFirstName");
if(getInput.value == ""){
window.alert("Please enter a first name");
getInput.focus();
return false;
}
}
And your submit button HTML become
<input type="submit" value="Click Me" onclick="check();">
Upvotes: 0