mardi 12 février 2019

Unable to toggle classes for model.IList checkbox list group through javascript

Long time listener, first time caller.

I have a simple bootstrap <div class="list-group checked-list-box"> that is being filled with checkboxes from a @model.IList.

<div class="form-group">
        @Html.Label("What needs to be done?", new { @class = "control-label col-md-2" })
        <div class="col-md-3">
            <div style="max-height: 300px; overflow: auto;">
                <div class="list-group checked-list-box">
                    @for (int i = 0; i < Model.AvailableJobs.Count; i++)
                    {
                        @Html.HiddenFor(m => m.AvailableJobs[i].id)
                        <label class="list-group-item far fa-circle" style="text-align: left;">
                            @Html.CheckBoxFor(m => m.AvailableJobs[i].IsSelected)
                            @Html.LabelFor(m => m.AvailableJobs[i].IsSelected, Model.AvailableJobs[i].name)
                            <span class="badge">+ @Html.ValueFor(m => m.AvailableJobs[i].time) min</span>
                        </label>
                    }
                </div>
            </div>
        </div>
    </div>

All I am wanting to happen is when the label is clicked, or even when the checkbox inside the label is checked/unchecked is for the label to toggle between some classes ('active far fa-circle/fa-check-circle'). I have tried multiple ways to get this handled and so far the below seems to be the cleanest way it should work.. but it doesn't exactly. I can click anywhere on the label and the checkbox will toggle but the script doesn't seem to fire unless I click directly on the checkbox's box

<script>
$(function () {
    $('.list-group-item').click(function () {
        if ($(this).hasClass('far fa-check-circle active'))
        {
            $(this).removeClass('far fa-check-circle active')
            $(this).addClass('far fa-circle')
        }
        else
        {
            $(this).removeClass('far fa-circle')
            $(this).addClass('far fa-check-circle active')
        }
    })
});

I have also tried changing the label class on the checkbox's state but everything seems to be following the first checkbox's state vs each nested checkbox.

<script>
    $(function () {
        $('.list-group-item').click(function () {
            if ($('input[type=checkbox]').prop('checked')) {
                $(this).removeClass('far fa-circle')
                $(this).addClass('far fa-check-circle active')
            }
            else {
                $(this).removeClass('far fa-check-circle active')
                $(this).addClass('far fa-circle')
            }
        })
    });
</script>

which I am pretty sure that is because I do not know how to select the appropriate checkbox in my script and I haven't had any luck finding what I am looking for on the net that made sense to me. Please help - Thanks!




Aucun commentaire:

Enregistrer un commentaire