简体   繁体   中英

Check if all text inputs are empty, show alert with for if/else statement?

beginner here. I'm trying to use a conditional to check whether if the text inputs have been filled out, otherwise if empty, prompt an alert but it doesn't appear to do anything? Is my JS poorly laid out? Here is my jsfiddle. https://jsfiddle.net/rtomino/4ywq9n3n/2/

Thank you!!

<div>
    <label for="cand1">Candidate 1</label>
    <input class="candidate" id="cand1" placeholder="Candidate">
</div>

<div>
    <label for="cand2">Candidate 2</label>
    <input class="candidate" id="cand2" placeholder="Candidate">
</div>

<div>
    <label for="cand3">Candidate 3</label>
    <input class="candidate" id="cand3" placeholder="Candidate">
</div>

The JS

function candidateNames() {
   var inputs = document.getElementsByTagName("input");
   var result = [];
 for ( var i = 0; i < inputs.length; i += 1 ) {
   result[i] = inputs[i].value;

  if (inputs === '' || null || 0) {
      alert('Need to fill inputs');
  }  
}
  document.getElementById("candidateName1").innerHTML = result[0];
  document.getElementById("candidateName2").innerHTML = result[1];
  document.getElementById("candidateName3").innerHTML = result[2];
}

You are checking if you inputs array is empty and not if the current input's value is empty.

See my inline comments.

function candidateNames() {
  var inputs = document.getElementsByTagName("input");
  var result = [];
  for ( var i = 0; i < inputs.length; i += 1 ) {
      result[i] = inputs[i].value;

      if (inputs[i].value == '') { // check if value is empty
          alert('Need to fill inputs');
          return; // stop the function
      }

}
    document.getElementById("candidateName1").innerHTML = result[0];
    document.getElementById("candidateName2").innerHTML = result[1];
    document.getElementById("candidateName3").innerHTML = result[2];
}

//Event listener to calculate button to call all above functions
document.getElementById("btn").addEventListener("click", calculateVotes, false);

function calculateVotes() {
  candidateNames();
}

You are checking for (inputs === '' || null || 0), which is wrong as inputs is an array, you need to do something like this:

function candidateNames() {console.log('here');
  var inputs = document.getElementsByTagName("input");
  var result = [];
  for ( var i = 0; i < inputs.length; i += 1 ) {
      result[i] = inputs[i].value;

      if (results[i] === '' || null || 0) {
          alert('Need to fill inputs');
      }

}
    document.getElementById("candidateName1").innerHTML = result[0];
    document.getElementById("candidateName2").innerHTML = result[1];
    document.getElementById("candidateName3").innerHTML = result[2];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM