I am creating a CGI form and I need to validate its content using javascript. Here is how it goes.
it have a table with 2 columns and 100+ rows. each columns contains 1 text box each, and the textbox name goes like, name1 & name1_var, name2 & name2_var and so on…like this but more than 100+ rows
`
`
now I need to make sure if in the first column is not NA but the second column can’t be NA. For that I have written something like below. But it is not working… need suggestion and help on this. <script> function validateForm() { var text = ""; var i = 1; while (i < 100) { nameid = "name" + i; nameid_var = "name" + i + "_var"; i++; var com1 = oForm.elements[nameid].value; var opt1 = oForm.elements[nameid_var].value; if (com1 != "NA" && opt1 == "NA") { alert("Name_var must be filled out"); return false; } } } </script>
It would be easier to just grab all of the elements at once for the validation (that way you don’t need to change the code if the number of inputs in your table changes
function validateForm() {
[].forEach.call( document.querySelectorAll('input[name^=name]'), function(el,p,l) {
if (el.name.indexOf('_var')>-1) {
if (el.value === "NA" && l[p-1].value !== "NA") {
alert("Name_var must be filled out");
return false;
}
}
});
}
of course the debugging alert will need to be replaced before it goes live.
As for why your code isn’t working - hard to tell as you haven’t posted all the JavaScript - you need an event listener to detect when the form has been submitted to call the JavaScript and you haven’t showed us how you coded that part.