Can someone please provide guidance on how to validate the array values in JavaScript? Below is the code I am currently using. The issue I am facing is that even after filling up all the values, I still receive a validation error message. Please advise me where I may be going wrong.
function chkdate() {
var x = document.forms["main"]["date"].value;
if (x == null || x == "") {
document.forms["main"]["date"].focus();
document.forms["main"]["date"].style.background = 'red';
alert("Date Cannot be empty");
return false;
}
}
function chkempty() {
var len = document.forms["main"]["item[]"].length;
if (len == undefined) {
var ic = document.forms["main"]["item[]"].value;
var iq = document.forms["main"]["qty[]"].value;
var ip = document.forms["main"]["price[]"].value;
if (ic == null || ic == "") {
document.forms["main"]["item[]"].focus();
document.forms["main"]["item[]"].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iq == null || iq == "") {
document.forms["main"]["qty[]"].focus();
document.forms["main"]["qty[]"].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ip == null || ip == "") {
document.forms["main"]["price[]"].focus();
document.forms["main"]["price[]"].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
} else for (i = 0; i < len; i++) {
var ica = document.forms["main"]["item[]"][i].value;
var iqa = document.forms["main"]["qty[]"][i].value;
var ipa = document.forms["main"]["price[]"][i].value;
if (ica == null || ica == "") {
document.forms["main"]["item[]"][i].focus();
document.forms["main"]["item[]"][i].style.background = 'red';
alert("Item Cannot be empty");
return false;
}
if (iqa == null || iqa == "") {
document.forms["main"]["qty[]"][i].focus();
document.forms["main"]["qty[]"][i].style.background = 'red';
alert("Qty Cannot be empty");
return false;
}
if (ipa == null || ipa == "") {
document.forms["main"]["price[]"][i].focus();
document.forms["main"]["price[]"][i].style.background = 'red';
alert("Price Cannot be empty");
return false;
}
}
}
Additional details:
Form name: main The input boxes item, qty, and price are dynamic rows based on the user's requirement. Thank you all.