Home > OS >  Check certain checkboxes when toggle is active
Check certain checkboxes when toggle is active

Time:10-20

Hi I have a form where people need to fill out on what days they work.

I have checkboxes from monday to sunday in a Vue file like this:

<a href="javascript:void(0)" 
    @click="setCurrentDay('monday')">
    <input name="checkbox_field0" id="checkbox_field0" type="checkbox"  v-model="monday">
    <label for="checkbox_field0">Monday</label>
</a>
<a href="javascript:void(0)" 
    @click="setCurrentDay('tuesday')">
    <input name="checkbox_field1" id="checkbox_field1" type="checkbox"  v-model="tuesday">
    <label for="checkbox_field0">Monday</label>
</a>

and so on...

Above this there is a toggle people can click if they work monday to friday. When they click this I want the checkboxes monday to friday to be (un)checked.

the toggle:

<div >I work monday to friday</div>

What is the best way to achieve this with Vue?

CodePudding user response:

You can uncheck checkboxes by doing:

// Unchecking one checkbox with id 'checkbox_field0'
document.getElementById("checkbox_field0").checked = false;

Now, you could wrap this inside a for..of loop, assuming you have an array of checkboxes (from monday to friday):

// 'week' is an array of checkboxes per day. 
for(day of week)
  day.checked = false;

Or, if you follow the same ID structure ('checkbox_field#') for the days of the week:

// Getting id as "checkbox_field{$i}"
for(let i=0; i<5; i  ) {
 const id = "checkbox_field"   i;
 document.getElementById(id).checked = false;
}

CodePudding user response:

solved my problem like this:

<label >                                                            
   <inputtype="checkbox" @click="fullWeek = !fullWeek">
   <span></span>
</label>
<a href="javascript:void(0)" 
    @click="setCurrentDay('monday')">
    <input name="checkbox_field0" id="checkbox_field0" type="checkbox"   v-model="weekdays['monday']">
    <label for="checkbox_field0">Monday</label>
</a>
<a href="javascript:void(0)" 
    @click="setCurrentDay('tuesday')">
    <input name="checkbox_field1" id="checkbox_field1" type="checkbox"   v-model="weekdays['tuesday']">
    <label for="checkbox_field0">Monday</label>
</a>
watch: {
            fullWeek() {
                this.weekdays.monday = this.fullWeek;
                this.weekdays.tuesday = this.fullWeek;
                this.weekdays.wednesday = this.fullWeek;
                this.weekdays.thursday = this.fullWeek;
                this.weekdays.friday = this.fullWeek;
            }
        }
  • Related