skip to Main Content

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


  1. You can add event listener to the input fields themselves to check if there is any change.

    const nameInput = document.getElementById("name");
    const lastnameInput = document.getElementById("last_name");
    
    nameInput.addEventListener("input", () => {
      const name = nameInput.value;
      const lastname = lastnameInput.value;
    
      if (name !== null && lastname !== null) {
        document.getElementById("continue_button").disabled = false;
      } else {
        document.getElementById("continue_button").disabled = true;
      }
    });
    
    lastnameInput.addEventListener("input", () => {
      const name = nameInput.value;
      const lastname = lastnameInput.value;
    
      if (name !== null && lastname !== null) {
        document.getElementById("continue_button").disabled = false;
      } else {
        document.getElementById("continue_button").disabled = true;
      }
    });
    
    Login or Signup to reply.
  2. Here is a very short way of doing it:

    const [btn,...inps]=["continue_button","name","last_name"].map(n=>document.getElementById(n));
    inps.forEach(el=>el.addEventListener("input",ev=>btn.disabled=inps.some(inp=>inp.value.trim()=="")))
    <input type="text" id="name" placeholder="first name">
    <input type="text" id="last_name" placeholder="last name">
    <button id="continue_button" disabled>go</button>

    The .map() in the first line of code collects the DOM elements, as specified by their id attributes, and packs them into the constants btn (the first returned value) and inps (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 the inps array having a trimmed ".value" attribut of "". If so, the button’s disabled attribute will be set to true, otherwise to false.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search