I have some inputs and a next button. At the moment I validated that the button is deactivated. If I fill in the name field, the button is activated.
var b = document.getElementById('button');
var input = document.getElementById("inputtext");
input.addEventListener("input", displayButton);
function displayButton() {
if (input.value === "") {
b.disabled = true;
} else {
b.disabled = false;
}
}
displayButton();
<input type="text" id="inputtext" placeholder="Enter name">
<input type="text" id="inputtext2" placeholder="Enter last_name">
<input type="text" id="inputtext3" placeholder="Enter country">
<button id="button">Next</button>
If I only want to verify that the first and last name are filled and not the city field, how would it be?
And also if I click on the disabled button insert a text that says "First fill all the fields".
2
Answers
You could add an event listener to all the
<input>
‘s, then on input, check ifsome()
inputs don’t have a value, use that to enable/disable the button. (Usingtrim()
so we ignore whitespaces)Regarding the "First fill all the fields" message, a
disabled
button can’t be clicked.You could add some logic to the
validate
function below that will set some message in another component.Edit: Based on OP’s comment, the same idea but with a
querySelcetorAll
that just targets 2 out of 3 fields. (I’ve renamed the fieldid
‘s to something more descriptive.Mark inputs as required
Use built-in form validation