0
votes

In my section-filter Vue component, I fill in my labels using v-for, and apply text from a "content" array in my data option. When a user clicks the checkbox, I want to get the value of "checked" (already done) and the text from it's parent label.

I've tried directly calling document.getElementById(id of label), but that only returns the first c.text and not the others.

I've tried setting the value attribute of the input to c.text similar to how v-for applies it.

//component for the filter section
Vue.component('section-filter', {

  template:

  `<div class="filter-container">
    <h3 id="filter-header">{{ header }}</h3>
    <div class="filter-main">
      <label id = "checkboxLabel" class="filter-checkbox" v-for="c in content">{{ c.text }}
        <input type="checkbox" checked @change="onChange">
        <span class="checkmark"></span>
      </label>
    </div>
   </div>`,

   methods: {
     onChange: function(e){
       var checked = e.target.checked;
       var text = //label text goes here

       console.log(checked + ' and ' + text);

     }
   },

   //set my text in data function so it can be reactive
   data: function() {
     return {
       header: 'Choose your sections',
       content: [
         { text: 'Health' },
         { text: 'Magazine' },
         { text: 'Opinion' },
         { text: 'Smarter Living' },
         { text: 'U.S.' },
         { text: 'World' }
       ]
     }
   }
})

false and Opinion //if opinion was unchecked

true and Opinion //if opinion was checked

2
Did you try with .parent() on you onChange method ? It should take the parent object - Jérôme
Are you referring to calling .parent( ) within the actual onChange method I've defined? Or the @change="onChange" section? I've tried setting text=document.getElementById(id of label).textContent but I could try text=document.getElementById(id of input).parent() - SciFiTy
Within the onChange method, try to do e.target.parentElement you should get the label element and then access to the content - Jérôme
That worked! Thank you very much. Do you need to submit it as an answer for me to accept and give you credit? - SciFiTy
I added an answer - Jérôme

2 Answers

1
votes

You could pass the text value as a parameter to the event handler

<input type="checkbox" checked @change="(event) => onChange(event, c.text)">

And then the handler would have the text

 onChange: function(e, text) {
0
votes

Inside your onChange method use e.target.parentElement to get the parent label element and then you should be able to access the label content

Something like this

methods: {
 onChange: function(e){
   var checkedLabel = e.target.parentElement;
   var text = checkedLabel.textContent;
   console.log(checked + ' and ' + text);
 }
},