This is my JS file to make the checkboxes, i just want that the checked prop of the checkbox updates itself base on the value of the input because my template engine renders the value of the boolean fields directly to my input value attr.
But is not working
$(document).ready(function () { $("input:checkbox").each(function (e) { console.log($(this).val()) value = $(this).val() $(this).prop('checked', value); }); }); <tr class="checkbox_widget_button"> <td> <div class="card-header"> {{item.validation}}</div> </td> <td> <form method="POST" name="validationFormName_{{item.id}}" id="validationFormId_{{item.id}}"> {% csrf_token %} <div class="card-body"> <input type="hidden" name="id" value="{{item.id}}"> <input type="hidden" name="user_id" value="{{user.profile.custom_user_id}}"> <label for="validation">{{item.validate|lower}}</label> <input type="checkbox" name="validation" value="{{item.validate|lower}}" id="validation"> </div> </form> </td> </tr>
Advertisement
Answer
Solved, main problem was {{item.validate|lower}} returned a “true” “false” string not boolean.
Just need to parse it and go to the most straight fordward solution.
{% for item in list_validations%} <tr class=""> <td> <div class="card-header"> {{item.validation}}</div> </td> <td> <div class="card-body"> <input type="checkbox" name="validation" value="{{item.validate|lower}}" id="validation_{{item.validation_id}}"> </div> </td> </tr> {% endfor %} $.fn.toggleCheckbox = function () { this.prop('checked', !this.prop('checked')); if (this.prop('checked')) { this.attr('value', true) } else { this.attr('value', false) } } $(document).ready(function () { $(".checkbox_widget_button").click(function (e) { if (e.target.tagName != 'INPUT') { $(this).find("input:checkbox").toggleCheckbox(); return false; } }); $("input:checkbox").each(function () { value = $(this).val() == "true"; //PARSE THE STRING TO BOOLEAN HERE SOLVES THE QUESTION checked = $(this).prop('checked'); if (value != checked) { $(this).toggleCheckbox(); } }); });