1

I'm having a hard time figuring out why all my checkboxes are becoming checked at once in my mapped vuejs tags.

I only want to check them one at a time but I can't remove the checkbox inputs from inside the

  • or my reference to student.someValue becomes undefined.

    <div class="modal-body modalBody" >
      <form @submit.prevent="makeExclusionGroup">
       <ul>
         <li class="listItems" v-for="(student, index) in students">
          {{student.first_name}}
          <input v-model="toExclude.selected" id="student.index" :value="student.full_name" type="checkbox"> 
         </li>                  
       </ul>
     </form>
    </div>
    

    2 Answers 2

    1

    This is happening because you have set a single model value toExclude.selected to all of the checkboxes, which means all of the checkbox now will have the same effect. So, to resolve this issue you can simply add a property like selected to student object so that each single checkbox will have its own value.

    Demo:

    new Vue({
      el: "#myApp",
      data: {
        students: [{text: 'Student 1', selected:false},{text: 'Student 2', selected:false},{text: 'Student 3', selected:false}]
      },
      methods: {
      }
    })
    ul li { display: inline-block; padding: 10px;}
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
    <div id="myApp">
      <ul>
         <li class="listItems" v-for="(student, index) in students">
          {{student.text}}
          <input v-model="student.selected" id="index" :value="student.text" type="checkbox"> 
         </li>                  
       </ul>
       <br/>
       <h5>Selected Options:</h5>
       <pre>{{students.map(s=>s.selected)}}</pre>
    </div>

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

    1 Comment

    thanks, suspected something had to be all 1 value, didn't realize what ;)
    1

    You need to have a v-model for each check box.

    All your checkboxes are referencing the same model.

    Try to change it to use a flag on the student

    <li class="listItems" v-for="(student, index) in students">
      {{student.first_name}}
      <input v-model="student.isSelected" id="student.index" :value="student.full_name" type="checkbox"> 
    </li>
    

    And then you can filter based on isSelected to get the selected students

    students.filter(student => student.isSelected)
    

    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.