Q:
Using the same function in 3 sub-pages for different input names
I have a form where I have to enter data into 3 input boxes. My JS script is:
What I want is that when the form is submitted the function 'validate' will be called and if any of the 3 input values is empty, it will return false and show an alert. In this example, I want an alert to show if I leave any of the 3 input boxes blank. The problem is that I have 3 inputs with the same name. When I leave any of them empty it always shows an error no matter which one of them I don't fill in.
Does anyone know how I can fix this problem?
A:
There is no way to do what you want.
You have to do one of the following:
Change the names of your input boxes so that they are unique, or
Wrap each of them in a div, and in the validation function check if any of the divs are not empty.
Edit: Here is the code I used to make the code working:
// JavaScript Code
function validate() {
// First, iterate over each input.
// Don't use 'class' as the selector. The ID should be unique for each input, so
// using it here is ok, but not advisable.
var inputs = document.forms["form1"].getElementsByTagName("input");
var totalErrors = 0;
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].value != "" || inputs[i].type == "text") {
return true;
} else {
// Add an error to the 'error' array.
totalErrors++;
}
}
if(totalErrors > 0) {
alert("Please fill in all fields");
return false;
} else {
alert("valid form");