I am bit confused of this integer comparison using jQuery
I have 2 input values.
so basically the inputed bid from user in the 2nd input field must be always higher than the current highest bid.
I used following jQuery code to compare between these 2 codes :
$(function(){
$('.bid').focusout(function(){
if($('.bid').val() <= $('.highestBid').val()){
$('.bidPlaced').prop('disabled', true);
}
else{
$('.bidPlaced').prop('disabled', false);
$('.buyItNow').prop('disabled', false)
}
});
});
The code works fine, but just now there is a bug I figured out
if the current highest bid is : $123 and the user input : $21 the function will not work
but if the user key in $122, the code will work
I found out that the jQuery code just compare the first value which in this case is $(1)23 to $(2)1.
can anybody tell me what is wrong with the jQuery code?
Thanks!
The val() method returns or sets the value attribute of the selected elements. When used to return value: This method returns the value of the value attribute of the FIRST matched element.
val()Returns: String or Number or Array. Description: Get the current value of the first element in the set of matched elements.
JQuery | type() method Return Value: It returns the string. Different obj return the following value for an object as a string. jQuery.type( true ) === “boolean”
When you get a value our of an input
element using jQuery .val()
, it will always be a string
. It doesn't matter that the input
element is type="number"
. The javascript value is a string
.
If you know your numbers will always be integers, you can parseInt
:
if (parseInt($('.bid').val()) <= parseInt($('.highestBid').val())) {
If your numbers possibly have decimal places, you can also use parseFloat
instead of parseInt
.
if (parseFloat($('.bid').val()) <= parseFloat($('.highestBid').val())) {
BTW, it is not jQuery that is behaving this way, it is the javascript language. All jQuery does is use javascript to read out the value of the input element in a convenient way, and give it back to you as a string.
It's up to you to know that these values are always string
s, and if you need to compare them as number
s, use javascript functions like parseInt
and parseFloat
to convert them into the correct javascript types before comparing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With