Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a checkbox as checked with Vue.js

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?

like image 635
Lovelock Avatar asked Oct 19 '22 15:10

Lovelock


People also ask

How do I check a checkbox in Vue?

Vue Set Checkbox as Checked To do this, we need to bind the checkbox value with the v-model directive. This can be done by applying simple logic, and that is. Set the checkbox value to true, so if the value is truthy, then the initial state will be checked.

How do I make check box checked?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

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

To watch for checkbox clicks in Vue. js, we can listen to the change event. to add the @change directive to the checkbox input to listen to the change event. Then we can get the checked value of the checkbox with e.


2 Answers

To set the state of the checkbox, you need to bind the v-model to a value. The checkbox will be checked if the value is truthy. In this case, you are iterating over modules and each module has a checked property.

The following code will bind the checkbox to that property:

<input type="checkbox" v-model="module.checked" v-bind:id="module.id">

If you'd like to know more about how v-model works in this situation, here's a link to the documentation about Form Input Binding.

like image 82
asemahle Avatar answered Oct 21 '22 05:10

asemahle


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).

like image 46
ricardoorellana Avatar answered Oct 21 '22 03:10

ricardoorellana