Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vuejs model for checkbox group

I have 2 arrays one for possible checkbox variants and one for already saved-checked boxes.VUEJS template for example

<ul>
                <li v-for="cit in possable">
                    <label>
                    <input  
                        type="checkbox"
                        :checked="savedcbx.indexOf(+cit.id)>-1"
                        :value="cit.id"/>
                    {{cit.rname}}
                    </label>
                </li>
            </ul>

And my question about how add new checkedbox to saved array or delete from saved array uncheckedbox&

like image 923
Sultan Zhumatayev Avatar asked Apr 21 '17 09:04

Sultan Zhumatayev


3 Answers

You only need one array to achieve toggling. From the Arrays section of Vue.js docs:

HTML:

<div id='example-3'>
  <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
  <label for="jack">Jack</label>
  <input type="checkbox" id="john" value="John" v-model="checkedNames">
  <label for="john">John</label>
  <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
  <label for="mike">Mike</label>
  <br>
  <span>Checked names: {{ checkedNames }}</span>
</div>

Vue app:

new Vue({
  el: '#example-3',
  data: {
    checkedNames: []
  }
})
like image 168
lauri108 Avatar answered Oct 08 '22 01:10

lauri108


I just put savedcbx to model and it works like in answer above. Vue great thing.

             <ul>
            <li v-for="cit in possable">
                <label>
                <input  
                    type="checkbox"
                    v-model="savedcbx"

                    //with model this not need too 
                    :checked="savedcbx.indexOf(+cit.id)>-1"
                    :value="cit.id"/>
                {{cit.rname}}
                </label>
            </li>
        </ul>
like image 4
Sultan Zhumatayev Avatar answered Oct 08 '22 01:10

Sultan Zhumatayev


So, assuming you have this data:

data() {
  return {
    possable: [1,2,3,4,5],
    savedcbx: [3,4]
   }
}

If you want to add a new item into savedcbx you just have to push it into the array (make sure it doesn't exist already)

addSavedId (id) {
  // Don't add it if it already exists
  if(this.savedcbx.indexOf(id) !== -1) return;

  this.savedcbx.push(id);
}

To remove an item:

removeSavedId (id) {
  let index = this.savedcbx.indexOf(id);

  // Nothing to remove if item is not in array
  if(index === -1) return;

  // Remove `index`
  this.savedcbx.splice(index, 1);
}

And now it's up to you when you call the addSavedId(id) and removeSavedId(id) functions and what is the parameter id.

like image 3
XCS Avatar answered Oct 08 '22 02:10

XCS