Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: Set checkboxes checked if statement is true

I had the following checkbox in my old handlebar view:

<div class="form-group">
    <input type='checkbox' name='xmlOnline[]' value="stepstone" class='' {{#if (ifIn 'stepstone' job.xmlOnline)}} checked="checked" {{/if}}> Stepstone
    <input type='checkbox' name='xmlOnline[]' value="karriere" class='' {{#if (ifIn 'karriere' job.xmlOnline)}} checked="checked" {{/if}}> Karriere
</div>

So if job.xmlOnline has "stepstone" as value, it should mark it as checked. Same goes for "karriere".

Now I am trying to achieve the same thing in Vue.js for my POST form. This is how the object "job" looks like: http://t2w-api.herokuapp.com/jobs/590c20d42b1c4300046bb1b9

So it can contain either "karriere", "stepstone", both or "null".

What I got so far in my component:

<div v-for="(xml, index) in job.xmlOnline">
    <input type="checkbox" :checked="xml == 'stepstone'"> Stepstone {{ index }}
    <input type="checkbox" :checked="xml == 'karriere'"> Karriere {{ index }}
</div>

Checkboxes get checked, but I have them duplicated. I also do not know how to add a v-model.

This is the source of my component. Did something similiar with "qualifications"/"responsibility": https://github.com/markusdanek/t2w-vue/blob/mdanek/2-auth-system/src/components/backend/JobEdit.vue

like image 468
mrks Avatar asked May 15 '17 15:05

mrks


1 Answers

A possible solution

<input type="checkbox" 
       :checked="job.xmlOnline && job.xmlOnline.includes('stepstone')"
       @change="onChange('stepstone', $event)"> Stepstone
<input type="checkbox" 
       :checked="job.xmlOnline && job.xmlOnline.includes('karriere')"
       @change="onChange('karriere', $event)"> Karriere

And the onChange method

methods:{
  onChange(value, $event){
    if (!this.job.xmlOnline)
      this.job.xmlOnline = []

    const index = this.job.xmlOnline.findIndex(v => v == value) 
    const checked = $event.target.checked

    if (checked && index < 0)
      this.job.xmlOnline.push(value)
    if (!checked && index >= 0)
      this.job.xmlOnline.splice(index, 1)
  }
}

Example.

like image 129
Bert Avatar answered Dec 25 '22 09:12

Bert