I am trying to validate a form using Javascript. The validation function aims to iterate through a variable number of input elements which have been named using an array format so that they come through properly in $_POST. However, I'm having trouble iterating through these elements with Javascript - does anybody know how to access these from simple Javascript?
Here's my validation function and a cut down version of my form to help illustrate what I'm trying to do:
<script type="text/javascript">
function validateForm() {
var vTotal = parseInt(document.getElementById('Total'));
var subtotal = 0;
var sub = document.getElementsByName('subqty');
for ( var i = 0; i < sub.length; i++ ) {
if ( sub[i].value != "" ) {
subtotal += parseInt(sub[i].value);
}
}
if ( subtotal != vTotal ) {
alert("Totals do not match, please check your math and try again.");
return false;
}
}
</script>
....
<form name="test" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" onsubmit="return validateForm();">
<input type="text" id="Total" value="100"><br>
<!-- there can be any number of subtotal inputs -->
<input type="text" name="subqty[1]" value="30"><br>
<input type="text" name="subqty[2]" value="10"><br>
<input type="text" name="subqty[3]" value="43"><br>
<input type="submit" value="Check Validation">
</form>
So far I am receiving an error that the parser cannot read the property "length" of type NULL - so it would appear that using getElementsByName on an array of input elements is not valid? Is there another way to do this?
subqty, so nothing matches. Just give the elements a common class, and use that instead. Javascript and HTML doesn't really care about "array named" elements, only PHP (and some other serverside languages) do.