Array[] form validation
array.length
keeps outputing 2007 arrays?
hmm.. I have a table which has of course 2 <tr>
1 for header and 1 for the values from the database
my table has a columns called code and description where ids are fCode[]
and fDesc[]
and each has an element
I have a code where I can clone a table row every time I click add. In every added row adds another fCode[]
and fDesc[]
.
2 rows = 2 fCode[], fDesc[]
At my javascript function I have this
function validate_pr_form(e) {
var fCode = document.forms[e].elements["fCode[]"];
var fDesc = document.forms[e].elements["fDesc[]"];
for ( i = 0; i < fCode.length; i++ ){
if ( fCode[i].value == "" ) {
alert("Please choose product code");
fCode[i].focus();
return false;
}
}
for ( i = 0; i < fDesc.length; i++ ){
if ( fDesc[i].value == "" ) {
alert("Please choose product description");
fDesc[i].focus();
return false;
}
}
e.submit();
}
开发者_Python百科
Whenever I load the page and hit submit button, I always get 2007 arrays but when I add another row, so it becomes 2 rows now (2 fCode[]
and 2 fDesc[]
) I get 2 arrays and those focuses in each array index normally.
My problem only goes with 1 row...
Any help is much appreciated.
thanks for the answer but I've already solved my problem by getting element's name like this
fCode = document.getElementsByName("fCode[]");
for ( var i = 0; i < fCode.length; i++ ){
if ( fCode[i].value == "" ) {
alert("Please choose 'Product Code'.");
fCode[i].focus();
return false;
}
}
Try this:
var fCode = document.forms[e].elements["fCode[]"];
if (typeof fCode.length != "number")
fCode = [fCode];
var fDesc = document.forms[e].elements["fDesc[]"];
if (typeof fDesc.length != "number")
fDesc = [fDesc];
精彩评论