Home  >  Q&A  >  body text

How to use the Enter key when working with checkboxes using Vue.js?

<p>I am learning Vue.js. In my application I have created a form with multiple checkboxes and a search function. The checkbox should be selected when the user uses the Tab key to focus the checkbox and presses the Enter key. </p> <pre class="brush:html;toolbar:false;"><template> <div> <div v-for="(ingredient, index) in filteredIngredients" :key="index" class="list-group-item px-md-4"> <div class="row px-3"> <div class="col-auto"> <input v-model="ingredient.checkbox" class="form-check-input" type="checkbox" @focus="checkFocus" /> </div> <div class="col ps-0"> <span class="mb-2 d-block text-gray-800"> <strong class="text-black-600">{{ ingredient.name }}</strong> </span> </div> </div> </div> </div> </template> <script> export default { methods: { methods: { checkFocus(event) { //What can I do here? }, }, }, } </script> </pre>
P粉106301763P粉106301763391 days ago441

reply all(1)I'll reply

  • P粉731977554

    P粉7319775542023-08-27 16:44:30

    If you want to do it in your own way, you can do this.

    export default {
      data() {
        return {
          filteredIngredients: [
            {name: "paper", checkbox: false},
            {name: "salt", checkbox: false}
          ]
        }
      },
      methods: {
        checkFocus(index) {
          this.filteredIngredients[index].checkbox = true;
        },
      }
    }
    <template>
      <div class="list-group-item px-md-4" v-for="(ingredient,index) in filteredIngredients" :key="index">
          <div class="row px-3">
              <div class="col-auto">
                  <input
                    class="form-check-input"
                    type="checkbox"
                    @keyup.enter="checkFocus(index)"
                    v-model="ingredient.checkbox"
                  />
              </div>
              <div class="col ps-0">
                  <span class="mb-2 d-block text-gray-800">
                      <strong class="text-black-600">{{ingredient.name}}</strong>
                  </span>
              </div>
          </div>
      </div>
    </template>

    If you want to do it using the Enter key, you can use @keyup.enter instead of @focus.

    reply
    0
  • Cancelreply