I am trying to validate a form without displaying the error message as an alert. innerHTML seems to be my best bet.
I have tried to implement it but I'm having no luck.
Here is the code.
Javascript:
<script> function validateForm() {
var x = "";
if (document.orderForm.firstName.value = "")
x += "Please enter your first name.";
document.getElementById('error').innerHTML = x;
return false;
}</script>
HTML:
<form name="orderForm" method="post" onsubmit="return validateForm()" action="processForm.html" >
<table>
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
</tr>
</table>
<div name="error" id="error">
</div>
</form>
Right now no error message is displayed.
I am trying to validate a form without displaying the error message as an alert. innerHTML seems to be my best bet.
I have tried to implement it but I'm having no luck.
Here is the code.
Javascript:
<script> function validateForm() {
var x = "";
if (document.orderForm.firstName.value = "")
x += "Please enter your first name.";
document.getElementById('error').innerHTML = x;
return false;
}</script>
HTML:
<form name="orderForm" method="post" onsubmit="return validateForm()" action="processForm.html" >
<table>
<tr>
<th colspan="2">Personal Information</th>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" id="firstName" size="30"></td>
</tr>
</table>
<div name="error" id="error">
</div>
</form>
Right now no error message is displayed.
Share Improve this question asked Oct 24, 2014 at 14:33 MacMac 3756 gold badges10 silver badges17 bronze badges3 Answers
Reset to default 3if (document.orderForm.firstName.value = "")
assigns the value ""
to document.orderForm.firstName.value
, then evaluates as a false value, so the if
statement will never be true.
Use a parison, not an assignment. ==
.
While you are at it, please learn about validators, labels, and CSS.
<script> function validateForm() {
if (document.orderForm.firstName.value == ""){ // == is parison... = is assignment
document.getElementById('error').innerHTML = "Please enter your first name.";
return false;
}
else
return true //Don't forget to return true if everything checks out
}</script>
<html>
<body>
<input type="text" id="Ifname">
<div id="fname"></div>
<button type="submit" onclick="validate()">Submit</button>
</body>
for a div having id="xyz" and will show the error for getting an input
field id="abc"
the function will call on the submit of button having onclick="validate()"
function validate(){
var x = "";
if (document.getElementById('Ifname').value == "")
{
document.getElementById('fname').innerHTML = "Email is Required!";
return false;
}
else
{
return true;
}
}
</script>
</html>
Please use this code to check validation for for 1 button.