I am using ionic
framework in vuejs
.
I have created a product page but it does not contain any form in it.
There is a radio button in the page which contains size of the product.
How can I access the selected value of the radio button created with ion-radio
when add to cart
button is pressed from that page.
I am new to vue.js
. Usually I used to get the value in jQuery using following method:
$('input[name=radioName]:checked').val()
How can I get the selected radio button value in vuejs
???
Here is the html part:
<ion-list v-if="product.size_maps">
<ion-radio-group>
<ion-row>
<ion-col
v-for="size in product.size_maps"
:key="size.id"
size="6"
id="product_size"
>
<ion-item>
<ion-label class="ion-no-margin">
{{ size.size.text }}
</ion-label>
<ion-radio slot="start" :value="size.size.id"></ion-radio>
</ion-item>
</ion-col>
</ion-row>
</ion-radio-group>
</ion-list>
I have created a method called addToCart
:
methods: {
addToCart(event) {
console.log(event);
// get radio button value here
}
}
Here is how I called the addToCart function in the button
<ion-button
color="primary"
fill="solid"
expand="block"
size="default"
v-on:click="addToCart"
>
Add To Cart
</ion-button>
Edit:
I tried to use v-model
to get the data. but since there is no input
tag available I could not add that.
If I added the v-model
in ion-radio
tag then all the radio buttons are being checked
I figured that v-model
will only work if you add v-model
in ion-radio-group
not in ion-radio
.
Here is the solution:
add v-model
in ion-radio-group
<ion-list v-if="product.size_maps">
<ion-radio-group v-model="selected_size"> <!-- notice the v-model here -->
<ion-row>
<ion-col
v-for="size in product.size_maps"
:key="size.id"
size="6"
id="product_size"
>
<ion-item>
<ion-label class="ion-no-margin">
{{ size.size.text }}
</ion-label>
<ion-radio slot="start" :value="size.size.id"></ion-radio>
</ion-item>
</ion-col>
</ion-row>
</ion-radio-group>
</ion-list>
then add selected_size
in data :
data() {
return {
...
selected_size: 0
};
}
then in method access this selected_size as usual
methods: {
addToCart(event) {
console.log(event);
// get radio button value here
console.log(this.selected_size);
}
}
I don't know the ionic framework, but I think I can see your problem. You need to bind your value of <ion-radio slot="start" :value="size.size.id"></ion-radio>
to the data-property, as follows: <ion-radio slot="start" v-model="size.size.id"></ion-radio>
and
data() {
return {
size: {
size: {
id: ''
},
},
};
},
The key here is to have an initial value as specified by ionic framework. I just added an empty string. You should also set an initial value to the radio-button, as follows:
In your method, you can then just access the value:
methods: {
addToCart(event) {
console.log(event);
// get radio button value here
console.log(this.size.size.id);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With