I’m working through a tutorial right now on form validation, and I would like assistance on why this function always returns the if condition.
<html>
<head>
</head>
<body>
<form id="form" action="#" method="post">
<fieldset>
<p>
First Name:
<input type="text" id="txt" />
</p>
<p> <input type="submit" value="submit" onclick="validate()" /> </p>
</fieldset>
</form>
<script type="text/javascript">
function validate()
{
var userName = document.getElementById("txt").value;
if (userName.length == 0)
{
alert("FINISH THAT UP");
return false;
}
else
{
alert("thanks, " + UserName);
}
}
</script>
</body>
It does reach the
elsepart when the textbox is not empty, but then it crash with error thus the form is being silently submitted.JavaScript is case sensitive –
UserNameis different thanuserNamethus undefined.Change to:
To avoid such problems, you can wrap the whole block with
try..catchlike this:With this in place, you would see “UserName is undefined”.
Live test case.
Also, on a side note – with your current code, even with empty value the form will still be submitted although you return false – that’s because you need to cancel the submit even:
You forgot the
returnkeyword in theonclickitself.