To check if a checkbox is checked in Vue:
- Create a boolean state variable to store the value of the checkbox.
- Use
v-model
to set up a two-way binding between the checkbox’s value and the state variable. - If the checkbox is checked, the state variable will be
true
. Otherwise, it will befalse
.
For example:
App.vue
<template>
<div id="app">
<input
type="checkbox"
v-model="agreement"
name="agreement"
/>
<label for="agreement">
I agree to the terms and conditions
</label>
<br /><br />
<button :disabled="!agreement">Continue</button>
</div>
</template>
<script>
export default {
data() {
return {
agreement: false,
};
},
};
</script>
The checked
property of the checkbox object indicates whether or not the checkbox is checked.
Every time the checkbox is checked or unchecked, the agreement
state variable will be automatically updated to true
or false
respectively.
We set the button
‘s disabled
prop to the negation of agreement
to disable and enable it when agreement
is true
and false
respectively.
Check if checkbox is checked with ref
In most cases, v-model
will be sufficient for checking if a checkbox if a checked in Vue. However, we can also use the ref
attribute to get the input value. We can set this attribute on any DOM element and use the $refs
property of the Vue instance to access the object that represents the element.
For example:
<template>
<div id="app">
<!-- 👇 Set "ref" prop to create new ref -->
<input
type="checkbox"
name="js"
ref="theCheckbox"
/>
<label for="js"> JavaScript </label>
<br />
<button @click="handleClick">Done</button>
<p v-if="message">{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return { message: '' };
},
methods: {
handleClick() {
// 👇 Access ref with "$refs" property
if (this.$refs.theCheckbox.checked) {
this.message = 'You know JS';
} else {
this.message = "You don't know JS";
}
},
},
};
</script>
We set an onClick
listener on the button. In this listener, we access the checkbox object using the ref, and use its checked
property to determine the message that should be shown to the user when the button is clicked.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.