检查所有文本输入是否为空,用if / else语句显示警告?

时间:2017-06-29 17:57:18

标签: javascript for-loop if-statement input

初学者在这里。我试图使用条件来检查文本输入是否已填写,否则如果为空,则提示警报,但它似乎没有做任何事情?我的JS布局不好吗?这是我的jsfiddle。 https://jsfiddle.net/rtomino/4ywq9n3n/2/

谢谢!

<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>

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];
}

2 个答案:

答案 0 :(得分:1)

您正在检查输入数组是否为空,如果当前输入的值为空则不会。

请参阅我的内联评论。

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

答案 1 :(得分:0)

您正在检查(输入===&#39;&#39; || null || 0),这是错误的,因为输入是一个数组,您需要执行以下操作:

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];
}