Javascript button is disabled until all fields are filled

I would appreciate help in resolving this. You must make the event listener work for the entire element. Thus, basically, when you fill in the first name, last name and all fields, then only the button should be turned on. Even if one of the fields is empty, the button must be disabled.

(function () { "use strict"; var knapp = document.getElementById('skicka'); knapp.disabled = true; var f=document.getElementById('fornamn'); var e=document.getElementById('efternamn'); var p=document.getElementById('passnr'); var n=document.getElementById('nat'); e.addEventListener('change',function(){ if(e.value==='' ){ knapp.disabled=true; } else{ knapp.disabled=false; } }); })(); 
+1
source share
2 answers

 let inputs = document.querySelectorAll('[type="text"]'), knapp = document.querySelector('#skicka') knapp.disabled = true for (i = 0; i < inputs.length; i++) { inputs[i].addEventListener('input',() => { let values = [] inputs.forEach(v => values.push(v.value)) knapp.disabled = values.includes('') }) } 
 <form> <input id=fornamn type=text><br> <input id=efternamn type=text><br> <input id=passnr type=text><br> <input id=nat type=text><br> <input type=button id=skicka value=Complete> </form> 

It will do it. I prefer the event handler to input not change so that you can see that the button is turned on as you type. Each time you enter something in any of the fields, it receives all the values ​​at once and adds them to the array. .includes() , new as ES6, is a method that checks for a specific array value and returns a boolean value.

+1
source
 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; } }); } 
0
source

Source: https://habr.com/ru/post/920481/


All Articles