dimanche 27 mars 2016

addClass to label if checkbox is checked, even on page refresh

How would I write the following in jQuery?:

When page load / (or "Continue" button is clicked, if makes more sense)
    Find input[type=checkbox] in each .block-container
        If input is checked
            add class to label
        If input is not checked
            remove class from label

I have a long line of checkboxes that follow this structure:

<div class="block-container">
    <div class="inner-container">
        <div class="form-group wpcf7-form-control wpcf7-checkbox checkbox-418">
            <div class="checkbox wpcf7-form-control wpcf7-checkbox checkbox-418 checked_check">
                <label class="">
                    <input type="checkbox" aria-invalid="false" value="Lorem ipsum title" name="checkbox-418" novalidate="novalidate" class="garlic-auto-save" checked="checked">
                    Lorem ipsum title</label>
            </div>
        </div>
    </div>
</div>

I had a toggleClass on them to add a color to the label when it's clicked, and a fancy checkbox icon (with the checkbox itself moved offscreen) but when the page is refreshed the class isn't applied even if the checkbox is still checked.

So if the user refreshes the page, the checkboxes they checked will remain checked, but the visual indicator (color, fancy checkbox) will appear to them to be unchecked, so they'll check it again and wind up unchecking the check.

Thanks in advance.

Edit to add something I tried:

$(document).ready(function() {
    $('.select-action').on('click',function() {
        $('.block-container input').each(function() {
            if ($("input[type=checkbox]").prop('checked')) {
                $(this).parent("label").addClass("symptomChecked");
                $(this).parent().parent().removeClass("empty_check").addClass("checked_check");
            } else {
                $("input").parent("label").removeClass("symptomChecked");
                $(this).parent().parent().removeClass("checked_check").addClass("empty_check");
            }
        });
    });
});




Aucun commentaire:

Enregistrer un commentaire