Reputation: 189
i have an a range number coming from server as below.
var max = 50;
var min = 25;
var uservalue = document.getElementById("userinput").value;// 35
User enters value in input box and i need to compare if entered value is inside the range or above the range. I have written code as below but not working.
if(uservalue<min || uservalue>max ){
alert("Error");
}else if (uservalue>min && uservalue<max)
alert("success");
What is the recommended conditions to see if user entered value is inside the rang or outside the range EDIT: user enters value inside and out side the range, i am looking for a condition to change the button state to yellow, red , green accordingly of user input value. Now it always turns to be out of range and hitting 1st condition
Upvotes: 1
Views: 2814
Reputation: 22490
If input type="text"
use with parseInt()
function check(){
var uservalue = parseInt(document.getElementById("userinput").value);
var max = 50;
var min = 25;
if (uservalue>min && uservalue<max){
console.log("success");
}else
{
console.log("Error");
}
}
<input type="text" id="userinput" onchange="check()">
click me..!
Upvotes: 0
Reputation: 587
use:
var uservalue = parseInt(document.getElementById("userinput").value);
or
if(+uservalue<min || +uservalue>max ){
...
}else if (+uservalue>min && +uservalue<max){
...
}
Upvotes: 1
Reputation: 37
if(uservalue < min || uservalue > max ){
alert("Error");
}
else {
alert("success");
}
This must work.
Upvotes: 1
Reputation: 718
I would did it upside-down
if(uservalue>=min && uservalue<=max ){
alert("In range");
}else if (uservalue>min){
alert("Too high");
}else alert("Too low:);
alert("success");
Upvotes: 1
Reputation: 155055
.value
will be a string value, not an integer. JavaScript's type-coercion is... complicated, so you'd be best-off doing explicit integer conversion with parseInt
and isNaN
:
var max = 50;
var min = 25;
var userValueStr = document.getElementById('userInput').value;
var userValueNum = parseInt( userValueStr );
if( !isNaN( userValueNum ) ) {
if( min <= userValueNum && userValueNum < max ) {
alert("Success");
}
else {
alert("Outside of range");
}
}
else {
alert("Value was not a number.");
}
Upvotes: 1
Reputation: 2540
You are reading uservalue in as a string, you need to convert it to an int:
uservalue = parseInt(uservalue)
Also, this should be enough:
if(uservalue < min || uservalue > max ){
alert("Error");
}
else {
alert("success");
}
Upvotes: 2