vendredi 2 mars 2018

jQuery prop checked has no effect on Materialize's checkboxes

I'm struggling with a strange issue here...There are up to ten checkboxes per group on my page which get rendered through a vue v-for loop. They are for polls which can but don't have to support multiselect. In this case, I'm trying to prevent multi selection. So this is the HTML for the checkboxes:

<div class="left-align">
  <p v-for="answer in polls[index+n].answers">
    <input type="checkbox" class="filled-in" 
      :name="'group'+n" 
      :id="answer._id" 
      :value="answer" 
       @change="lockBoxes(n, answer._id)" 
       v-model="selected_answers"/>
    <label :for="answer._id"></label>
  </p>
</div>

The colons just tell that the attributes are getting binded. So there are currently 5 polls on my page which means 5 groups of checkboxes where each checkbox has a defined name in the group. In this case, the code above will get rendered to the DOM into the following:

<div class="left-align">
  <p>
    <input name="group0" id="5a95784b23fc2e03cc34aba3" class="filled-in" value="[object Object]" type="checkbox"> 
    <label for="5a95784b23fc2e03cc34aba3">A</label>
  </p>
  <p>
    <input name="group0" id="5a95784b23fc2e03cc34aba2" class="filled-in" value="[object Object]" type="checkbox"> 
    <label for="5a95784b23fc2e03cc34aba2">B</label>
  </p>
  <p>
    <input name="group0" id="5a95784b23fc2e03cc34aba1" class="filled-in" value="[object Object]" type="checkbox"> 
    <label for="5a95784b23fc2e03cc34aba1">C</label>
  </p>
</div>

Don't worry about the value field. That's not supposed to get rendered but I need it in my vue component and I haven't found a way not to render it yet. Anyway, I use jQuery to select all the other checkboxes in the group:

lockBoxes: function(group, selected) {
  $(":input[name^="+'group'+group+"]:not(#"+selected+")").each( function () {
    $(this).prop('checked', false);
  })
}

This gets triggered as soon as one checkbox of a group is checked (see the @change in the checkbox). I already logged the elements and it's getting the correct ones. This code gets any other checkboxes except for the currently selected one in the group and is supposed to uncheck the others. There might be a better or more efficient solution, but seeing as vue renders several polls with multiple checkboxes I didn't find a better way of doing it. Anyway, it's not doing anything, I can still check them all. The funny thing though is that if I use the disabled prop instead, it works fine. I'm not sure, but I think this might be an issue with Materialize. I also tried to use removeAttr() and trigger() to update the element, but that didn't do the trick either...

Thanks for your help in advance.




Aucun commentaire:

Enregistrer un commentaire