Checkboxes/radios/selects
Checkboxes, radio buttons and dropdowns each bind to the type of data that fits them best.
In this page:
Syntax
<input type="checkbox" v-model="checked">
<input type="radio" value="option" v-model="picked">
<select v-model="selected">
<option value="option">text</option>
</select>
Checkboxes/radios/selects
A single checkbox binds to a boolean, several checkboxes bind to an array, a radio group binds to one value and a select binds to the chosen option value (or an array with multiple). Use :value on options and inputs to bind non-string values.
Note:
Bind several checkboxes to one array to collect all checked values.
Example: Checkboxes/radios/selects
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<label><input type="checkbox" v-model="agree"> Agree</label>
<label><input type="checkbox" value="js" v-model="langs"> JS</label>
<label><input type="checkbox" value="py" v-model="langs"> Python</label>
<label><input type="radio" value="S" v-model="size"> S</label>
<label><input type="radio" value="L" v-model="size"> L</label>
<select v-model="color"><option value="red">Red</option><option value="blue">Blue</option></select>
<p>{{ agree }} | {{ langs }} | {{ size }} | {{ color }}</p>
</div>
<script>
Vue.createApp({ data() { return { agree: false, langs: [], size: "S", color: "red" }; } }).mount("#app");
(async () => {
const boxes = document.querySelectorAll("input");
for (const i of [0, 1, 2, 4]) { boxes[i].click(); await Vue.nextTick(); }
const sel = document.querySelector("select"); sel.value = "blue"; sel.dispatchEvent(new window.Event("change"));
await Vue.nextTick();
console.log(document.querySelector("p").textContent);
})();
</script>
</body>
</html>
<!-- Output:
Rendered: Agree JS Python S LRedBluetrue | [ "js", "py" ] | L | blue
console: true | [
"js",
"py"
] | L | blue
-->
Live Example
Related Topics
Common Mistakes
- Using a boolean where an array is needed
- Forgetting the value attribute
- Not setting an initial value for select
Chapter Summary
- One checkbox is a boolean
- Many checkboxes give an array
- Radios give one value
- select binds the chosen value
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: