Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VueJS Checkbox Model Array of Ints

I have an issue with VueJS 1.0, and this behavior works in VueJS 2.0. In VueJS 1.0 if I have a list of integers and have a checkbox v-model bound to it, the list of integers will not map as a checked attribute.

Here is the HTML

<div id="app">
  <div class="col-sm-offset-3 col-sm-4 clearfix text-center">
    <h4>On Each Day of The Week</h4>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox1" v-model="schedules[0].by_days" value="1"> M
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox2" v-model="schedules[0].by_days" value="2"> Tu
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox3" v-model="schedules[0].by_days" value="3"> W
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox4" v-model="schedules[0].by_days" value="4"> Th
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox5" v-model="schedules[0].by_days" value="5"> F
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox6" v-model="schedules[0].by_days" value="6"> Sa
    </label>
    <label class="checkbox-inline">
      <input type="checkbox" id="inlineCheckbox7" v-model="schedules[0].by_days" value="7"> Su
    </label>
    <div class="clearfix"></div>
  </div>
  By Days: {{ schedules[0].by_days.join(', ') }}
</div>

Then here is the JavaScript:

new Vue({
    el: '#app',
    data: {
        schedules: [
            {
            'by_days': ["1", 2, 3]
          }
        ]
    }
})

The output will have "1" correctly checkboxed, but 2 & 3 are integers and will not show as checked. In VueJS 2.0 this works, but not VueJS 1.0.

A full JSFiddle is available here: https://jsfiddle.net/qf5gqsg6/

like image 451
Joseph Montanez Avatar asked Oct 29 '16 10:10

Joseph Montanez


2 Answers

Change your data ["1",2,3] into [1,2,3]

Change your your checkbox input element value into :value

like image 90
Kornelius Kristian Rayani Avatar answered Nov 06 '22 02:11

Kornelius Kristian Rayani


I found the answer, I need to set the bind the value to the input instead of just relying on the value from the input.

So instead of:

<input type="checkbox" v-model="schedules[0].by_days" value="2"> M

It needed to be:

<input type="checkbox" v-model="schedules[0].by_days" v-bind:value="2"> M

Of course this doesn't work if there is a list of mixed strings and integer numbers, but it works in my case where everything was an integer.

like image 26
Joseph Montanez Avatar answered Nov 06 '22 03:11

Joseph Montanez