-
Create
itemsCount
property on your component’s data object:data: function { return { itemsCount: "" } }
-
Use
v-model
attribute to assign the value of your input to theitemsCount
property.<input type="number" class="col-1 form-control" v-model="itemsCount" />
-
Refactor
addToCart()
function to takeitemsCount
value into account.addToCart() { let quantity = this.itemsCount !== "" ? this.itemsCount : 1 this.$store.dispatch('addProductToCart', { product: this.product, quantity: parseInt(quantity) }) }
Solution 1 :
Solution 2 :
Have you considered something like this?
<input type="number" v-model="quantity" />
And later your method
addToCart() {
this.$store.dispatch("addProductToCart", {
product: this.product,
quantity: this.quantity // this.quantity here
});
}
Problem :
So basically I am trying to add the product into the cart. Currently, I am able to do it when the button is clicked. But I also want to add it when the amount was added in the input field. So if there is no amount the quantity should be increased once and if the amount was entered like 5, after clicking the button the quantity needs to be increased 5 times.
For this my html:
<div class="row number-of-tickets">
<input type="number" class="col-1 form-control" />
<button class="btn button col-2" @click="addToCart()">Add to cart</button>
</div>
And my add to cart method:
addToCart() {
this.$store.dispatch('addProductToCart', {
product: this.product,
quantity: 1
})
}
So currently, I can add when the button is clicked but I am not able to add the amount when the input is enrtered. I am quite new in vue if you can help me, that would be great.
Comments
Comment posted by vuejs.org/v2/guide/forms.html#number
you can use v-model.number=”itemsCount” instead of v-model=”itemsCount”
Comment posted by magic bean
Thanks for your solution, but the problem is in your solution, now I lost my click button functionality without entering any input. And it doesnt add, for example, I enter 5 and it is showing 5 at the cart, when I add again 5 instead of 10, it is showing 55.
Comment posted by user14967413
Probably it is necessary to use