Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript else if statement doesn't work

I'm working on a website for school and i need to make a shopping cart.When i check if the quantity asked is grater than the amount available it returns true even if it's not. for example 3 > 12 is true and i get the error message. I have misspelled "available".. i know :( Here's my function :

function add_to_cart() {

   jQuery ('#modal_errors').html("");

   var size = jQuery('#size').val();
   var quantity = jQuery('#quantity').val();
   var avaliable = jQuery('#avaliable').val();
   var error = '';
   var data = jQuery('#add_product_form').serialize();

   if( size == '' || quantity == '' || quantity == 0 ){
      error +='<p class = "text-danger text-center">You need to select a size and quantity.</p>';
      jQuery('#modal_errors').html(error);
      return;
  }
  else if(quantity > avaliable){
      error +='<p class = "text-danger text-center">There are only '+avaliable+' avaliable and you asked for '+quantity+'.</p>';
      jQuery('#modal_errors').html(error);
      return;
  }
}

This returns the message(for my case) : " There are only 12 avaliable and you asked for 3.

This might be a noob mistake but i can't figure it out. Any help please?

Edit ->>

Used

var quantity = Number.parseInt(jQuery('#quantity').val());
var avaliable = Number.parseInt(jQuery('#avaliable').val());

and it works but now im in mists again :D

I get the values like this

    <div class="form-group">
                <div class="col-xs-3"><label for="quantity">Quantity:</label>
                  <input type="number" class="form-control" id="quantity" name="quantity" min="0"></div><br><div class="col-xs-9">&nbsp;</div>
              </div>

input type being number i assumed i dont need to convert from string to number. doesn't the input type number = to an actual number than can be compared or multiplyed or whatever?

Thanks for the answer :)

like image 721
Teo Alex Avatar asked Sep 13 '26 00:09

Teo Alex


1 Answers

Because your quantity and avaliable are strings, not numbers. And the comparison is going through strings.

Try to do

var quantity = Number.parseInt(jQuery('#quantity').val());
var avaliable = Number.parseInt(jQuery('#avaliable').val());

Edited

or you can do parsing only in the condition, if you want to use them as strings

else if(Number.parseInt(quantity) > Number.parseInt(avaliable)){

}
like image 135
Suren Srapyan Avatar answered Sep 14 '26 13:09

Suren Srapyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!