Reputation: 79
I have this condition using JavaScript, I have 2 text boxes where I'll compare the input ( inputs are numbers). The condition is when textbox 2 is less than textbox 1 it will have an alert message that says textbox2 must be greater than textbox2. So when the input is like this
textbox2 > textbox1
15 > 1 = alert pops out
15 > 2 = not ok
15 > 3 = not ok
15 > 4 = not ok
15 > 5 = not ok
15 > 6 = not ok
15 > 7 = not ok
15 > 8 = not ok
15 > 9 = not ok
15 > 10 = ok
onwards is ok.
Why is it that when it compares 2 to 9 it doesn't alert anything?
Here is my condition:
if(textbox2.value < textbox2.value)
{
document.getElementById("lblStatus1").innerHTML = 'Pay1 must be greater than To1';
}
Upvotes: 1
Views: 68
Reputation: 39248
The problem here is that you are comparing strings, which is different than comparing numerical values.
"15" is < "2" Because it's evaluated alphabetically character by character . The leading '1' in '15' causes '15' to be < '2'
Upvotes: 3
Reputation: 810
You are having an issue related to validating strings. Try to parse the values as numbers:
Value 1<input type="text" id="text1" /><br />
Value 2<input type="text" id="text2" /><br /><br />
<input type="button" value="Validate" onclick="doValidate();" />
function doValidate() {
var value1 = new Number(document.getElementById("text1").value);
var value2 = new Number(document.getElementById("text2").value);
if (value2 < value1)
alert("Value 2 must be higher than Value 1!");
}
Notice the usage of new Number() in JavaScript. This effectivelly turns the string into a number (if it is a valid number).
Upvotes: 0
Reputation: 9388
Are you parsing your input values? If not, you're doing a comparison against strings which would result in an issue. Something like this:
parseInt(inputVal1, 10) > parseInt(inputVal2, 10)
Upvotes: 1
Reputation: 17203
If you copy and pasted your code...
You're comparing the same values textbox2.value and textbox2.value.
Upvotes: 0
Reputation: 59232
You are comparing strings. Which will not work as you intended to.
Use parseInt()
:
if(parseInt(textbox2.value) < parseInt(textbox2.value))
{
document.getElementById("lblStatus1").innerHTML = 'Pay1 must be greater than To1';
}
Upvotes: 1