Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get checked value of checkbox if use array as a model in vue

Tags:

vue.js

vuejs2

I wonder if I use array as model for multiple-checkbox list, how can I check which items is checked and which are unchecked efficiently rather than compare one by one with that array?

<ul>
<li v-for="task in tasks">
<input type="checkbox" :id="task.title" :value="task" v-model="selectedTasks" @change="handleTasks(task)">
<label :for="task.title">{{task.title}}</label>
</li>
</ul>


new Vue({
  data: {
      tasks: [
        { title: 'Go to the store' },
        { title: 'Clean the house' },
        { title: 'Learn Vue.js' }
      ],
      selectedTasks: []
  },
})
like image 250
Kuan Avatar asked Jul 19 '18 23:07

Kuan


People also ask

When a checkbox is selected what will be its value?

If a checkbox is marked or checked, it indicates to true; this means that the user has selected the value. If a checkbox is unmarked or not checked, it indicated to false; this means that the user has not selected the value.

Which method checks if an item is selected in a checkbox?

In order to check if a checkbox is checked or unchecked, we can used the isSelected() method over the checkbox element. The isSelected() method returns a boolean value of true if the checkbox is checked false otherwise.

How do you check checkbox is checked or not in Vuejs?

prop('checked'); which will return true if checkbox is checked or not.


1 Answers

You could add a property to each task (e.g., checked) and bind that to each input's v-model, making it trivial in code to check whether a task is checked/selected:

new Vue({
  el: '#app',
  data() {
    return {
      tasks: [
        { title: 'Go to the store', checked: false },
        { title: 'Clean the house', checked: false },
        { title: 'Learn Vue.js', checked: false }
      ]
    };
  },
  methods: {
    clearCheckedTasks() {
      this.tasks = this.tasks.filter(x => !x.checked);
    }
  }
})
<script src="https://unpkg.com/[email protected]"></script>

<div id="app">
  <ul>
    <li v-for="task in tasks">
      <input type="checkbox" :id="task.title" v-model="task.checked">
      <label :for="task.title">{{task.title}}</label>
    </li>
  </ul>
  
  <button @click="clearCheckedTasks">Clear checked tasks</button>
  
  <h3>tasks (live)</h3>
  <pre>{{tasks}}</pre>
</div>
like image 120
tony19 Avatar answered Sep 27 '22 22:09

tony19