Reputation: 355
I'm trying to validate the html form and return an alert if any of the elements are empty on submission. When I test this script, the from is sent to the server regardless whether any of the fields are filled in. Any help will be appreciated.
<script type="text/javascript">
/* <![CDATA [ */
function validateForm()
{
for(var i=0; i < document.salesRecords.elements.length; i++)
{
if(document.salesRecords.elements[i].value == null || document.salesRecords.elements[i].value == "")
{
alert("Error " + name + " must be given a value");
return false;
}
else return true;
}
}
/* ]]> */
</script>
HTML
<form action ="some_action.php" name="salesRecords" method="post">
Client = <input type="text" name="client" value="" /> </br>
Date = <input type="text" name="date" value="" /> </br>
Value = <input type="text" name="amount" value="" /> </br>
<input type="submit" value="Submit" onclick="validateForm();"/>
Upvotes: 0
Views: 55
Reputation: 38456
In your Submit
button's onclick
attribute, you have to actually use the return value with return validateForm();
, not just call the method:
<input type="submit" value="Submit" onclick="return validateForm();"/>
UPDATE (additional logic issue in the javascript)
After looking at your javascript, you have a logic issue that will cause the form to submit even when some fields are "not valid":
else return true;
This line is inside your for
loop and will return true
after the very first form-field validates properly.
The fix is to simply remove the line and add return true;
after the loop finishes:
function validateForm() {
for(var i=0; i < document.salesRecords.elements.length; i++) {
if(document.salesRecords.elements[i].value == null || document.salesRecords.elements[i].value == "") {
alert("Error " + name + " must be given a value");
return false;
}
}
return true;
}
Upvotes: 1
Reputation: 5412
Try this:
Html:
<input type="submit" value="Submit" onclick="return validateForm();"/>
Javascript:
function validateForm()
{
for(var i=0; i < document.salesRecords.elements.length; i++)
{
if(document.salesRecords.elements[i].value == null ||
document.salesRecords.elements[i].value == "")
{
alert("Error " + document.salesRecords.elements[i].getAttribute("name") + " must be given a value");
return false;
}
}
}
Upvotes: 2