Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.val() integer datatype comparison

I am bit confused of this integer comparison using jQuery

I have 2 input values.

  • input type="number" class="highestBid" value=
  • input type="number" min="0" class=" bid" name="bid" id="bid"

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!

like image 814
Foster Avatar asked Dec 07 '14 19:12

Foster


People also ask

What does val () in JQuery do?

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.

Does val () return a string?

val()Returns: String or Number or Array. Description: Get the current value of the first element in the set of matched elements.

What is type in JQuery?

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”


1 Answers

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 strings, and if you need to compare them as numbers, use javascript functions like parseInt and parseFloat to convert them into the correct javascript types before comparing.

like image 184
danludwig Avatar answered Oct 28 '22 11:10

danludwig