Search code examples
javascriptinputdisabledisabled-input

Button enabling before all inputs are filled and disabling when all inputs are filled


I want to disable a button until all of the inputs on the page are filled. I am doing this using only JavaScript without a form in html (changing it to a form messes with my other code). Currently, the button will enable when some of the inputs are filled (one or more), but if all of the inputs are filled the button disables. The button is also disabled when no inputs are filled. I would like to disable the button until all the inputs are filled so that the user cannot submit it empty or having filled only some inputs.

JavaScript code that checks if the input is filled:

document.addEventListener('DOMContentLoaded', function(){
    const required = document.querySelectorAll('.input');

    function checkSubmit(button){
        let isValid = true;
        for(let i = 0; i <required.length; i++){
            isValid = isValid && !!required[i].value;
            console.log("is enabled");
        }
        button.disabled = isValid;
        console.log("is disabled");
    }

    function inputHandler(button){
        return function(){
            checkSubmit(button);
        };
    }

    //gets all the quiz_buttons                                                                                                                                      enableChecking();
    const quizButton = document.querySelectorAll('.quiz_button');
    for (const button of quizButton){
        button.disabled = true;
        for(let i = 0; i < required.length; i++){
            required[i].addEventListener("input", inputHandler(button));
        }
        button.addEventListener('click', (event) =>
            check_quiz(event.target.id));
    }
});

Solution

  • I've changed and simplified your existing code to work as expected, all the buttons will only be enabled if all the inputs are filled.

      document.addEventListener('DOMContentLoaded', function () {
      const inputs = document.querySelectorAll('input');
      const quizButtons = document.querySelectorAll('button');
    
      for (const i of inputs) {
        i.addEventListener("input", checkSubmit);
      }
    
      for (const b of quizButtons) {
        b.disabled = true;
        b.addEventListener('click', (event) =>
          check_quiz(event.target.id));
      }
    
      function checkSubmit() {
        let isValid = true;
        for (const i of inputs) {
          isValid = isValid && !!i.value;
        }
    
        for (const b of quizButtons) {
          b.disabled = !isValid;
        }
      }
    
    });
    

    a basic jsfiddle demo showing this in action.

    Hope this helps!