I have a form and I am doing some form validation using JavaScript.
function validate() {
let arr = [];
arr[0] = form.name ;
arr[1] = form.mobNumber ;
arr[2] = form.email ;
arr[3] = form.query ;
for (let num = 0; num < arr.length; num++){
if (arr[num].value == ""){
arr[num].placeholder = "This field is mandatory";
arr[num].style.backgroundColor = "rgba(0, 0, 255, 0.1)";
arr[num].classList.add('redPlaceholder');
return false;
}
}
}
.redPlaceholder::placeholder {
color: red;
font-style: italic;
font-family: 'Roboto' sans-serif;
}
<form name="form" method="post" netlify id="form" onsubmit="return validate()" >
<input type="text" name="name" placeholder="Name"><br>
<input type="email" name="email" placeholder="E-mail"><br>
<input type="number" name="mobNunber" placeholder="Contact Number"><br>
<textarea name="query" placeholder="Your Query" rows="5"></textarea><br>
<input type="submit" name="submit" value="Submit">
</form>
In the js part, I have an empty array and later add input fields of the form by accessing them through their name. In the for loop I am checking if each of the input field is filled or not. If not, then I have some code to execute.That code block is running perfectly.
The problem is that when I click submit button with all fields empty, the code in the for loop runs only once - for the first input field. I think that there is some problem with the loop though I have checked the syntax several times.