0

I'm trying to create a form in which one text input field will have disabled attribute if a checkbox is checked. I tried:

new Vue({
  el: "#app",
  data: {
    isChecked: false,
    name: null
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<div id="app">
  <input type="text" v-model="name" :class="{disabled: isChecked}" placeholder="disabled if box checked">
  <input type="checkbox" v-model="isChecked">
</div>

4
  • have you tried :disabled=isChecked instead of :class="{disabled: isChecked}" ? Commented Oct 2, 2018 at 21:20
  • :disabled=isChecked does the job. Thanks! Commented Oct 2, 2018 at 21:24
  • Do you mind if I create an answer so people who find this question can get the answer more easily ? Commented Oct 2, 2018 at 21:26
  • Definitely. I was about to ask you to post an answer, maybe with a bit elaboration. Commented Oct 2, 2018 at 21:30

1 Answer 1

1

Instead if using a conditional class, you can just use the property disabled and make it dynamic by adding a : in front of it and binding it to the isChecked variable. Your code will then look like this :

<div id="app">
  <input type="text" v-model="name" :disabled="isChecked" placeholder="disabled if box checked">
  <input type="checkbox" v-model="isChecked">
</div>
Sign up to request clarification or add additional context in comments.

2 Comments

There are missing quotations in :disabled="isChecked"
According to the doc it's not required, but is said to be avoided as it makes developpers get the habit of not adding spaces in the attributes values (vuejs.org/v2/style-guide/…). Thanks for pointing it out, I never really thought about that, I will add them.

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.