I have been googling and playing with every combination I know but I cannot get my checkboxes to be initialised as checked.
Example:
<ul class="object administrator-checkbox-list">
<li v-for="module in modules">
<label v-bind:for="module.id">
<input type="checkbox" v-model="form.modules" v-bind:value="module.id" v-bind:id="module.id">
<span>@{{ module.name }}</span>
</label>
</li>
</ul>
An example of the modules data:
[
{
"id": 1,
"name": "Business",
"checked": true
},
{
"id": 2,
"name": "Business 2",
"checked": false
},
]
What can I do to initially set the checked status of the checkboxes?
This question is related to
javascript
vue.js
Let's say you want to pass a prop to a child component and that prop is a boolean that will determine if the checkbox is checked or not, then you have to pass the boolean value to the v-bind:checked="booleanValue"
or the shorter way :checked="booleanValue"
, for example:
<input
id="checkbox"
type="checkbox"
:value="checkboxVal"
:checked="booleanValue"
v-on:input="checkboxVal = $event.target.value"
/>
That should work and the checkbox will display the checkbox with it's current boolean state (if true checked, if not unchecked).
I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented
native events from occurring with:
<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
:checked="confirmed.indexOf(render.uuid) > -1"
:value="render.uuid"
/>
removing the .prevent
from the @click
handler fixed my issue.
I had similar requirements but I didn't want to use v-model
to have the state in the parent component. Then I got this to work:
<input
type="checkbox"
:checked="checked"
@input="checked = $event.target.checked"
/>
To pass down the value from the parent, I made a small change on this and it works.
<input
type="checkbox"
:checked="aPropFrom"
@input="$emit('update:aPropFrom', $event.target.checked)"
/>
In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:
<input
type="checkbox"
v-model="toggle"
true-value="yes"
false-value="no"
>
I use both hidden and checkbox type input to ensure either 0 or 1 submitted to the form. Make sure the field name are the same so only one input will be sent to the server.
<input type="hidden" :name="fieldName" value="0">
<input type="checkbox" :name="fieldName" value="1" :checked="checked">
Source: Stackoverflow.com