Reputation:
Hi I am new to javascript.
I am trying to implement some javascript form validation I am trying to use the technique used here: http://www.w3schools.com/js/tryit.asp?filename=tryjs_form_validation to test for empty field in the form and using an alert to warn users But it is not work for me When i submit an empty form proceeds to the jsp file and the javascript does not catch the error
here is my index.html file where the form is
<html>
<body>
<head>
<script>
function validateForm()
{
var stoneField=document.forms["bmiForm"]["stone"].value;
var poundsField=document.forms["bmiForm"]["pounds"].value;
var kgsField=document.forms["bmiForm"]["kgs"].value;
var feetField=document.forms["bmiForm"]["feet"].value;
var inchesField=document.forms["bmiForm"]["inches"].value;
if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
{
alert("Please enter a weight and height");
return false;
}
else
{
return true;
}
}
</script>
</head>
<form name ="bmiForm" action="PrintBMI.jsp" onsubmit="return validateForm()" method=post style="width:250px;">
<fieldset>
<legend>BMI Calculator</legend>
<h3>Enter your weight</h3>
Stone <input type = text name = "stone" size = 1 maxlength = 2>
Pounds <input type = text name = "pounds" size = 1 maxlength = 2>
<br>
<strong>OR</strong>
<br>
KGs <input type = text name = "kgs" size = 1 maxlength = 3>
<h3>Enter your height</h3>
Feet <input type = text name = "feet" size = 1 maxlength = 1>
Inches <input type = text name = "inches" size = 1 maxlength = 2>
<br>
<strong>OR</strong>
<br>
Metres <input type = text name = "metres" size = 1 maxlength = 4>
<p><input type=submit value = "Get BMI">
</fieldset>
</form>
</body>
</html>'
Does anyone see what I'm doing wrong. Thanks for your time.
Upvotes: 1
Views: 1708
Reputation: 1023
USE == for comparing value.
replace below block of code in your code.
if ( stoneField == null || stoneField == "" && poundsField == null || poundsField == "" && kgsField == null || kgsField == "" && feetField == null || feetField == "" && inchesField == null || inchesField == "" )
Upvotes: 0
Reputation: 3671
if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
{
alert("Please enter a weight and height");
return false;
}
Use === inside if, not =
Upvotes: 0
Reputation: 193251
Replace =
to ===
in this code:
if ( stoneField = null || stoneField = "" && poundsField = null || poundsField = "" && kgsField = null || kgsField = "" && feetField = null || feetField = "" && inchesField = null || inchesField = "" )
Read about Comparison Operators
Upvotes: 1