skip to Main Content

I’m rather new to JavaScript and I’m having a little problem with this if/then/else if statement. I tried a few things below but am stuck. Does anyone have any ideas?

if (variant.inventory_management == "shopify" && variant.inventory_policy != "continue") {
    if (variant.inventory_quantity < 10) {
      $lowStockAmount.html('Last few remaining! only ' + variant.inventory_quantity + ' left');
    } else if (variant.inventory_quantity < 1)  {
      $lowStockAmount.html("We're sold out, Don't worry! <a href='#'>click here</a> to be notified when it's back in stock.");
    }
  }

I tried == 0 as well but I end up with the same thing: it just shows the last few remaining! only 0 left but if it is 0, I’d like it to show the sold out message.

2

Answers


  1. Think about the logic as it is right now. If variant.inventory_quantity is 0, the “else if” statement will never run, because it will only be checked if variant.inventory_quantity is NOT less than 10.

    Here’s the fix. Change this line:

    if (variant.inventory_quantity < 10) {

    to this:

    if (variant.inventory_quantity < 10 && variant.inventory_quantity > 0) {

    Login or Signup to reply.
  2. Here is a simplified answer to your problem. If the quantity is 0, show the “We’re sold out” info. Else, if the quantity is not 0 but less than 10, show the “Last few remaining” info. Otherwise don’t show anything.

    var quantity = 10;
    
    if (quantity === 0) {
        console.log("We're sold out, Don't worry! <a href='#'>click here</a> to be notified when it's back in stock.");
    } else if (quantity < 10) {
        console.log('Last few remaining! only ' + quantity + ' left');
    }
    

    The quantity == "0" will not work, because you’re comparing a number with a string.

    EDIT: quantity == "0" will work but is not a proper style of comparing two values.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search