Darren
Darren

Reputation: 223

Bind specific checkbox to disable specific dropdown in VueJS?

I have a table, each row has a checkbox, name, another checkbox, and dropdown. I want to have the dropdown disabled by default, and only enable it when check the first checkbox.

Here's the HTML:

<tbody>
    <tr v-for="item in Items" v-bind:id="item.ID">
        <td>
            <!-- check this checkbox and enable/disable the dropdown -->
            <input type="checkbox" v-on:click="onSelect($event)" v-model="item.Selected" />
        </td>
        <td>
            {{ item.Name }}
        </td>
        <td>
            <input type="checkbox" v-model="item.isActive" /><
        <td>
            <!-- enabled/disabled depending on if checkbox is checked -->
            <select v-bind:disabled="">
                <option value="foo">foo</option>
                <option value="bar">bar</option>
            </select>
        </td>
    </tr>
</tbody>

Currently, the onSelect($event) method will check the second checkbox in the same row when checked.

Here's my JavaScript:

var vm = new Vue({
    el: '#app',
    data: {
        items: items
    },
    methods: {
        onSelect: function (event, id) {
            setTimeout(function () {
                var idx = $(event.target).closest('tr').index();
                if (items[idx].Selected) {
                    items[idx].isActive = true;
                }
            }, 100);
        }
    }
});

Is there a way to bind the enabling/disabling of the dropdown to a checkbox with VueJS 2/JavaScript/jQuery?

Upvotes: 2

Views: 2228

Answers (1)

kristoffer_remback
kristoffer_remback

Reputation: 570

You don't actually need to use jQuery or events for this, rather you can simply use Vue's data binding for this. Simply set v-model="item.Selected" on the first checkbox, and then on the select, set v-bind:disabled="!item.Selected".

HTML:

<!-- index.html -->
<div id="app">
  <table>
    <tbody>
      <tr v-for="item in items">
        <td>
          <!-- check this checkbox and enable/disable the dropdown -->
          <input type="checkbox" v-model="item.Selected"/>
        </td>
        <td>
          {{ item.Name }}
        </td>
        <td>
          <!-- enabled/disabled depending on if checkbox is checked -->
          <select v-bind:disabled="!item.Selected">
            <option value="foo">foo</option>
            <option value="bar">bar</option>
          </select>
        </td>
      </tr>
    </tbody>
  </table>
</div>

JavaScript:

// app.js
const vm = new Vue({
  el: '#app',
  data() {
    return {
      items: [
        { ID: 1, Name: 'name 1', isAcitve: false, Selected: false },
        { ID: 2, Name: 'name 2', isAcitve: false, Selected: false },
        { ID: 3, Name: 'name 3', isAcitve: false, Selected: false },
      ]
    }
  },
})

I've attached a pen which displays this.

Upvotes: 4

Related Questions