I am running this code. Here, I am trying to get error statement after pressing submit button but I am unable to get any error notification on html web page after typing name in 2 letters(name.length<5 will give error notification). but, I am getting nothing. Can someone look upon this code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content ="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> practice</title>
</head>
<body>
<h1><b>Welcome to the your page.</b></h1>
<form action="#" name="myForm"
method="post" onsubmit="return validateForm()">
What is your name?:
<input id="name" type="text" name="fname" placeholder="Required" required>
<span class ="formerror"></span>
<input type="submit" value="Submit">
</form>
</body>
<script>
function seterror(id,error)
{
element= document.getElementById(id);
element.getElementsByClassName
("formerror")[0].innerHTML=error;
}
function validateForm(){
var returnval = true;
var name = document.forms['myform']["fname"].value;
if(name.length<5)
{seterror("fname","length of name is too short");
returnval = false;}
//console.log('name sf');
//return false;
return returnval;
}
</script>
</html>
CodePudding user response:
One way you can do this is to use the minLength
(1) attribute on the input:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content ="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title> practice</title>
</head>
<body>
<h1><b>Welcome to the your page.</b></h1>
<form action="#" name="myForm"
method="post" onsubmit="return validateForm()">
What is your name?:
<input id="name" type="text" name="fname" placeholder="Required" required minLength="5">
<span class ="formerror"></span>
<input type="submit" value="Submit">
</form>
</body>
CodePudding user response:
First of all, you have a problem in your seterror
function, but the error can't reach the console because your form will always be submitted. No matter what. So, to see what's happening, you should prevent default behaviour:
onsubmit="event.preventDefault();return validateForm()"
Then you will get an error: Cannot read properties of undefined (reading 'fname')
.
// 'myform' should be 'myForm'
document.forms['myform']
Your mistake #2: Uncaught TypeError: Cannot read properties of null (reading 'getElementsByClassName')
.
// 'element' should be 'document'
element.getElementsByClassName("formerror")[0].innerHTML = error;
Full working code:
function seterror(id, error) {
document.getElementsByClassName("formerror")[0].innerHTML = error;
}
function validateForm() {
var returnval = true;
var name = document.forms['myForm']["fname"].value;
if (name.length < 5) {
seterror("fname", "length of name is too short");
returnval = false;
}
return returnval;
}
Next steps
Don't use inline event handlers, they are harder to use. Instead you should handle events in modern way with .addEventListener()
.