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.
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
There will be times where you will want to write commands that handle different decisions in your code. For example, if you are coding a bot, you can have it respond with different messages based on a set of commands it receives. In this article, I...
Also, I would suggest using some functions and using those because you have repetition in your code.
Functions are one of the fundamental concepts in programming. They let us write concise, modular, reusable, and maintainable code. They also help us obey the DRY principle when writing code. In this article, you will learn what functions are in...
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
1 Like
Hey @jwilkins.oboe and @Ayesha_Khan , Thank for your help. I appreciate it!
2 Likes
system
Closed
November 6, 2024, 12:28am
6
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.