Skip to content Skip to sidebar Skip to footer

Javascript Disable Button Until All Fields Are Filled

would appreciate some help solving this. Need to make the event listener work for all the element. So basically when you fill out name, last-name i.e all the fields then only the

Solution 1:

let d = document, [inputs, knapp] = [
    d.querySelectorAll('[type="text"]'),
    d.querySelector('#skicka')]
knapp.disabled = truefor (i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener('input',() => {
    let values = []
    inputs.forEach(v => values.push(v.value))
    knapp.disabled = values.includes('')
  })
}
<form><inputid=fornamntype=text><br><inputid=efternamntype=text><br><inputid=passnrtype=text><br><inputid=nattype=text><br><inputtype=buttonid=skickavalue=Complete></form>

This will do it. I prefer the eventhandler on input not change, so that you can see the button being enabled as you type. Every time you enter anything in any of the fields it will get all values at once and add them to an array. The .includes(), new as of ES6, is a method that checks for a specific value of an array and returns a boolean.

Solution 2:

var elements = document.querySelectorAll("#fornamn, #efternamn, #passnr, #nat");
for (var i = 0; i < elements.length; i++) {
  elements[i].addEventListener("change", function() {
    if(document.getElementById("fornamn").value == "" && document.getElementById("passnr").value == "" && document.getElementById("nat").value = "" && document.getElementById("efternamn").value == "") {
        knapp.disabled=true;
    } else {
        knapp.disabled=false;
    }
  });
}

Post a Comment for "Javascript Disable Button Until All Fields Are Filled"