I have a form where I save first and last name in the localstore.
If the name and surname are filled, I enable the button and if not, it remains disabled.
How do I get this validation to run in real time, on each change made by the user, at the moment I have this
Next
const name = localStorage.getItem('name');
const last_name = localStorage.getItem('last_name');
if(name === null || last_name === null ) {
document.getElementById("continue_button").disabled = true;
}else{
document.getElementById("continue_button").disabled = false;
}
2
Answers
You can add event listener to the input fields themselves to check if there is any change.
Here is a very short way of doing it:
The
.map()
in the first line of code collects the DOM elements, as specified by theirid
attributes, and packs them into the constantsbtn
(the first returned value) andinps
(all other returned values).In the second line the event-listener for the "input" event is added to all elements of
inps
. The attached listener function then checks whether it can find at least one element of theinps
array having a trimmed ".value" attribut of""
. If so, the button’sdisabled
attribute will be set totrue
, otherwise tofalse
.