I have a form with first name, last name and email, and i need to make an alert if a field is empty. I made an alert but it comes up for every field that is empty.
This is the js:`
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
alert("All fields must be filled!");
}
}
});
`
The form-control class is on all the input fields. If i leave all 3 inputs empty, the alert comes up 3 times.
Please help, my brain is stuck.
you can use array.some on inputs get by querySelectorAll() to raise only one alert if one fields is not empty
document.querySelector("#book").addEventListener("click", () => {
let inputs = document.querySelectorAll(".form-control");
if ([...inputs].some(input => input.value === '')) {
alert("All fields must be filled !");
}
});
<input class="form-control" />
<input class="form-control" />
<button id="book">validate</button>
You can simply use an array to get all errors inside a single array and after the loop finish then you can give the final alert.
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
let errors = [];
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
errors.push("Error "+ i);
}
}
if(errors != []){
alert("All fields must be filled!");
}
});
If you want a generic message, you can just display it once, and even stop the loop:
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
alert("All fields must be filled!");
break; // <-- alert was shown, nothing else to do
}
}
});
If you want to show a single message, but specific to the missing field(s), you have to collect them in the loop, and show the single message after, something like
document.querySelector("#book").addEventListener("click", () => {
let inp = document.querySelectorAll(".form-control");
let missing=[];
for (let i = 0; i < inp.length; i++) {
if (inp[i].value == "") {
missing.push(inp[i].name);
}
}
if(missing.length) {
alert("Please fill the following fields too: "+missing.join());
}
});