Skip to content
Advertisement

How to prevent checking same value checkboxes using Vue.js?

I just started learning vue.js, I have such a problem, I have multiple checkboxes some of them have the same value, As a result, checkboxes of the same value are checked at the same time, How can this problem be solved?

var app = new Vue({
  el: '#app',
  data: {
    checkedNames:[]
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" id="john" value="Jack" v-model="checkedNames">
<label for="jack">John</label>
<input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>

</div>

Advertisement

Answer

Try this:

const app = new Vue({ 
  el: '#app', 
  data: () => ({ checkedNames:[] }),
  computed: { 
    names: function() { return this.checkedNames.filter(e => e !== false); } 
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <input type="checkbox" id="jack" true-value="Jack" v-model="checkedNames[0]">
  <label for="jack">Jack</label>
  <input type="checkbox" id="jack1" true-value="Jack" v-model="checkedNames[1]">
  <label for="jack1">Jack</label>
  <input type="checkbox" id="mike" true-value="Mike" v-model="checkedNames[2]">
  <label for="mike">Mike</label><br>
  <span>Checked names: {{ names }}</span>
</div>
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement