Reputation: 133
I need the validInput function to check if all input entered are numberic character/
The issue is when the first if statement return true, the function seems to skip the input check.
For example, if I enter 1 for input1, then "a" for input2, -3 for input3, the function will return true and shows the result.
https://codepen.io/regnagleppod/pen/NdWLYx
html:
<label>Starting Number: </label>
<input id="input1" type="text">
<br>
<label>Ending Number: </label>
<input id="input2" type="text">
<br>
<label>Step: </label>
<input id="input3" type="text">
<button onclick="return playButton()" id="play">Display Evens</button>
js:
function playButton(){
run();
if (validInput()){
showResult();
}
};
function validInput(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var z = document.getElementById("input3").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
Upvotes: 0
Views: 51
Reputation: 117
your mistake is very trivial you are comparing <=0 and isNaN with the value of x, i.e input1.(value) , Change the 2nd and 3rd if (condition) it will work.
Here is the changed code
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
Upvotes: 0
Reputation: 135
I have modified your code,please modified code
function playButton(){
run();
if (validInput()){
showResult();
}
};
function validInput(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var z = document.getElementById("input3").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
Upvotes: 1
Reputation: 1712
Mohit are correct,
Change the function as follows,
function validInput(){
var x = document.getElementById("startingNum").value;
var y = document.getElementById("endingNum").value;
var z = document.getElementById("step").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
Upvotes: 1