13

In vue2 js, I want to use a checkbox with a v-model.

<input type="checkbox" value="test" :checked="selected"/>

I want the value of the checkbox to be test, however I want the 2 way binding with the prop called selected which is a boolean. However the above only does 1 way binding. How can I fix this?

4
  • could you provide more code and more details please? Commented Nov 18, 2018 at 23:18
  • A standard checkbox is like this <input type="checkbox" name="vehicle3" value="Boat" checked> and v-model seems to alter the value attribute. So how would that work when the checked attribute needs to be 2-way bind? Commented Nov 18, 2018 at 23:20
  • Are you looking for a solution like this: stackoverflow.com/questions/50350254/… Commented Nov 18, 2018 at 23:21
  • thats using a framework, im just talking about regular vue. Commented Nov 18, 2018 at 23:24

3 Answers 3

17

Use v-model instead of :checked

new Vue({
  el: '#app',
  data: {
    selected: false
  }
});
<script src="https://unpkg.com/vue@2"></script>
<div id="app">
  <input type="checkbox" value="test" v-model="selected">
  <div>Selected: {{selected}}</div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

In vue you can use "true-value" and "false-value":

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no" />

or

<input
  type="checkbox"
  v-model="toggle"
  :true-value="dynamicTrueValue"
  :false-value="dynamicFalseValue" />

cf.: https://vuejs.org/guide/essentials/forms#checkbox-1

Comments

0

To set up a checkbox with two-way binding in Vue 2, use v-model directly. Here’s a simple way to do it:

<template>
  <div>
    <input type="checkbox" v-model="isChecked" />
    <p>Checked: {{ isChecked }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isChecked: false  // Initial state of the checkbox
    };
  }
};
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.