JQuery.val () comparing integer data type
I am a little confused about this integer comparison using jQuery
I have 2 input values.
- input type = "number" class = Value "highBid" =
- input type = "number" min = "0" class = "bid" name = "bid" id = "bid"
so basically the rate entered from the user in the second input field should always be higher than the current maximum rate.
I used the following jQuery code to compare between these two 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 now there is an error that I figured out
if the current maximum bid is $ 123 and user input is $ 21, the function will not work
but if the user key is $ 122 the code will work
I found out that the jQuery code is just comparing the first value, which in this case is $ (1) 23 to $ (2) 1.
can someone tell me what is wrong with the jQuery code?
Thank!
source to share
When you get the value of our element input
using jQuery .val()
, it will always be string
. It doesn't matter what the item is input
type="number"
. The javascript value is string
.
If you know that your numbers will always be integers, you can parseInt
:
if (parseInt($('.bid').val()) <= parseInt($('.highestBid').val())) {
If your numbers can have decimal places, you can also use parseFloat
instead parseInt
.
if (parseFloat($('.bid').val()) <= parseFloat($('.highestBid').val())) {
By the way, it's not jQuery that behaves this way, it's javascript language. All jQuery really uses javascript to conveniently read the value of an input element and return it to you as a string.
You are aware 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 to correct javascript before matching.
source to share