Home > Net >  How do I disable a button before any fields have been checked?
How do I disable a button before any fields have been checked?

Time:02-01

Not sure what I am doing wrong here, I am calling the function incorrectly or do the html tag have to specific for the disable to work? I am trying to disable the next button before any fields have been checked, I also only want one checkbox to be selected at a time. I can get the only one checkbox to be selected a time but this stop me from disabling the button cause I can't have the field be inputs.

enter image description here

<div>
    <button @click="handleCompanySize(100)">
        <CheckIcon v-show="companySize === 100"/>
    </button>
    <button @click="handleCompanySize(101)">
        <CheckIcon v-show="companySize === 101"/>
    </button>
</div>

<button :disabled="handleCompanySize" @click="next">
    Next
</button>

CodePudding user response:

This is a simple requirement and looks like you overthinked about it. You can use a computed property in the :disabled attribute which returns true/false based on the checkbox selection.

Live Demo :

new Vue({
  el: '#app',
  data: {
    employees: [ 
      { "id": 1, "text": "0 - 1" },
      { "id": 2, "text": "2 - 10" }, 
      { "id": 3, "text": "11 - 50" }, 
      { "id": 4, "text": "50 - 100" },
      { "id": 5, "text": "> 100" }
    ],
    selected: []
  },
  computed: {
    disableBtn() {
      return !this.selected.length ? true : false
    }
  },
  methods: {
    uniqueCheck(e) {
      this.selected = [];
      if (e.target.checked) {
        this.selected.push(e.target.value);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <h4>Employee Selection</h4>
    <table>
        <tr v-for="employee in employees">
            <td>
                <input type="checkbox" v-model="selected" :value="employee.id" @change="uniqueCheck">
            </td>
            <td>{{ employee.text }}</td>
        </tr>
    </table>
    <button :disabled="disableBtn">
      Next
    </button>
</div>

  • Related