3

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 button should get enabled, Even if one of the fields is empty the button should get 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;
 }
  });

  })();

2 Answers 2

7

let d = document, [inputs, knapp] = [
    d.querySelectorAll('[type="text"]'),
    d.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>

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.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

It works but not as specified. I mean the task is to enable the button if all fields are field not only one of them. With this code, the button gets enabled as soon as I write something in one of the fields.
Answer updated. And also can use class selector to the elements for the onChange event so that there is no need to loop through the elements for adding the event listener
a = is missing, should be ...ntById("nat").value == ""... and yeah, not working for me either.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.