jQuery-UI Button Set Initial Icon

2019-09-13 06:48发布

问题:

I have the following jQuery script to transform a checkbox into a jQuery-UI button and set up the icons to be displayed. It also changes the icon when the button is clicked. It all works fine. However I cannot seem to hit on the correct syntax to set the initial icon based on the initial checked state of the checkbox.

function setCheckBoxImages() {
        $(".check-box-image").button({
            icons: { primary: 'ui-icon-check' },
            text: false
        }).change(function () {
            $(this).button("option", {
                icons: { primary: this.checked ? 'ui-icon-check' : '' }
            });
        });
    };

<input class="check-box-image" type="checkbox" checked="@item.IsBusinessHours" id="checkbox1" disabled/><label for="checkbox1"></label>

EDIT: Here is my final working markup and script as per accidentalgenius answer below:

@Html.CheckBox(@cbMobileId, @item.IsMobile, new { @class = "check-box-image", disabled = "disabled" })<label for="@cbMobileId">    

function setCheckBoxImages() {
        var checkboxes= $(".check-box-image");

        checkboxes.button({
            text: false
        }).change(function () {
            $(this).button("option", {
                icons: { primary: this.checked ? 'ui-icon-check' : 'ui-icon-minus' }
            });
        });

        checkboxes.each(function () {
            $(this).change();
        });
    };

回答1:

You could loop through all of the jQuery Buttons and call the change function for each one.



回答2:

maybe your function has not been called. try this on your javascript

$(document).ready(function(){
    $(".check-box-image").button({
        icons: { primary: 'ui-icon-check' },
        text: false
    }).change(function () {
        $(this).button("option", {
            icons: { primary: this.checked ? 'ui-icon-check' : '' }
        });
    });
});


回答3:

When are you calling setCheckBoxImages()? Without seeing the rest of the code it is hard, but try calling it on document.ready.

You should be setting the initial icons based on the status of the checkbox:

function setCheckBoxImages() {
        var check = $(".check-box-image");
        check.button({
            icons: { primary: check.is(':checked') ? 'ui-icon-check' : '' },
            text: false
        }).change(function () {
            $(this).button("option", {
                icons: { primary: this.checked ? 'ui-icon-check' : '' }
            });
        });
    };