Reputation: 85
I am trying to create a products page with a forum that shows the price of the item, the name of the item and also the quantity with buttons to add or subtract from the quantity field.
I have no idea where to begin, I thought I'd do some looking into different types of buttons and form input types but none of them seem to have what I need.
I was wondering if anyone can point me to the right direction so I can figure out how these buttons are changing the quantity field and how I can make a plus and minus button which appears next to the quantity.
Here is a picture of what I mean:
Upvotes: 0
Views: 19604
Reputation: 10801
Use JavaScript to increase and decrease the input value:
const minusButton = document.getElementById('minus');
const plusButton = document.getElementById('plus');
const inputField = document.getElementById('input');
minusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue - 1;
});
plusButton.addEventListener('click', event => {
event.preventDefault();
const currentValue = Number(inputField.value) || 0;
inputField.value = currentValue + 1;
});
<button id="minus">−</button>
<input type="number" value="0" id="input"/>
<button id="plus">+</button>
Here what happens in the JS code. First it gets references to the HTML elements using the id
HTML attribute and the document.getElementById
JS function. Then it adds functions which are executed when one of the buttons is clicked. Inside the functions, the default button browser action (submitting the form) is cancelled, the input value is read, increased/decreased and put back to the input.
Upvotes: 7