Home > database >  HTML Checkbox: automatic checkable prop update based on value with Javascript Jquery
HTML Checkbox: automatic checkable prop update based on value with Javascript Jquery

Time:08-13

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 >
                    <td>
                        <div > {{item.validation}}</div>
                    </td>
                    <td>
                        <form method="POST" name="validationFormName_{{item.id}}" id="validationFormId_{{item.id}}">
                            {% csrf_token %}
                            <div >
                                <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>

CodePudding user response:

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 >
<td>
<div > {{item.validation}}</div>
</td>
<td>
<div >
<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();
        }
    });
});
  • Related