Rashad
Rashad

Reputation: 1344

Can't reset checked radio value to defaut value ( Vue js)

By default, I use local pickup option, with value 1. When user changes to free delivery, there will be some condition: if zip codes are valid, then it will changed to free delivery, if not, alert message will be displayed and local pickup will be checked again. The problem is that, I can set a default delivery value to 1 if zipcode is not suitable. But radio displays checked option as 2.

<label v-for="(del, index) in delivery" :key="index">
    <input type="radio" name="del" :value="del.value" v-model="defaultDelivery" @change="changeDelivery(del.value)">{{ del.label }}
</label>


export default {
    data () {
        return {
            delivery: [
                {value: 1, label: 'Local pickup'},
                {value: 2, label: 'Free Delivery'}
            ],
            accepted_zips: [
              12345,
              12346
            ],
            defaultDelivery: 1,
            zip_code: 78745
        }
    },
    changeDelivery: function(val) {
        if(val == 2 && !this.accepted_zips.includes(this.zip_code))
        {
            this.defaultDelivery = 1 //it should set 1 as checked again! But it is not aplied
            alert('Sorry but currently we don't cover your area.')
        }
    },

Upvotes: 0

Views: 88

Answers (1)

Roy J
Roy J

Reputation: 43881

Note that the apostrophe in "don't" is closing your string, and you didn't put your method in a methods section. Correcting for that, your code works fine for me.

new Vue({
  el: '#app',
  data() {
    return {
      delivery: [{
          value: 1,
          label: 'Local pickup'
        },
        {
          value: 2,
          label: 'Free Delivery'
        }
      ],
      accepted_zips: [
        12345,
        12346
      ],
      defaultDelivery: 1,
      zip_code: 78745
    };
  },
  methods: {
    changeDelivery(val) {
      if (val == 2 && !this.accepted_zips.includes(+this.zip_code)) {
        this.defaultDelivery = 1 //it should set 1 as checked again! But it is not aplied
        alert('Sorry but currently we don\'t cover your area.')
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>ZIP code <input v-model="zip_code"></div>
  <label v-for="(del, index) in delivery" :key="index">
    <input type="radio" name="del" :value="del.value" v-model="defaultDelivery" @change="changeDelivery(del.value)">{{ del.label }}
</label>
</div>

Upvotes: 1

Related Questions