HTML and JavaScript. This is a simple one, but I'm just a Newbie. Can you please help me?

How can I display in the console if the cartQuantity value touches < 0, or it becomes -1, -2, -3 …
I want to display in the console ‘Cart Quantity: No more item in the cart!’ instead of just counting -1, -2, -3 downwards.

111

Here is the code:

<button onclick="
  console.log(`Cart Quantity: ${cartQuantity}`);
">Show Quantity</button>

<button onclick="
  cartQuantity ++;
  console.log(`Cart Quantity: ${cartQuantity}`);
">Add to Cart</button>

<button onclick="
  cartQuantity += 2;
  console.log(`Cart Quantity: ${cartQuantity}`);
">+2</button>

<button onclick="
  cartQuantity += 3;
  console.log(`Cart Quantity: ${cartQuantity}`);
">+3</button>

<button onclick="
  cartQuantity += 4;
  console.log(`Cart Quantity: ${cartQuantity}`);
">+4</button>

<button onclick="
  cartQuantity += 5;
  console.log(`Cart Quantity: ${cartQuantity}`);
">+5</button>

<button onclick="
  cartQuantity = 0;
  console.log('Cart was reset.');
  console.log(`Cart Quantity: ${cartQuantity}`);
">Reset Cart</button>

<button onclick="
  cartQuantity --;
  console.log(`Cart Quantity: ${cartQuantity}`);
">Remove from cart</button>

<button onclick="
  cartQuantity -= 2;
  console.log(`Cart Quantity: ${cartQuantity}`);
">-2</button>

<button onclick="
  cartQuantity -= 3;
  console.log(`Cart Quantity: ${cartQuantity}`);
">-3</button>

<script>
  let cartQuantity = 0;
</script>
1 Like

Hi @musclexd !

Welcome to the forum!

use an if statement

Also, I would suggest using some functions and using those because you have repetition in your code.

Hope that helps

1 Like

Hi @musclexd
You can create a generic function for this and use the “if” condition inside that function.

function showQuantity() {
if(cartQuantity < 0)
console.log("No more item in the cart");
else console.log(cartQuantity)
}

You can pass above function to the onClick event of “Show Quantity” button.

Similarly, for adding items to cart, you can define another generic function like this:

function addItemToCart() {
cartQuantity++;
}

I hope this will help, if you need anything else I’ll be more than happy to help :slight_smile:

1 Like

Hey @jwilkins.oboe and @Ayesha_Khan , Thank for your help. I appreciate it! :heart:

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.