Reputation: 283
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];
}
Upvotes: 0
Views: 2703
Reputation: 9808
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];
}
Upvotes: 0
Reputation: 1856
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();
}
Upvotes: 1