Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle the icon on a jQuery UI button when clicked

I'm writing a web app for a mobile phone and I want all of the checkboxes to be buttons with either a "check" or "cross" on them, along with the text of the checkbox. I've got a working solution using jQuery UI, but it doesn't seem every elegant. Can anyone suggest any improvements?

Here's the code:

$(function () {
    $("input[type=checkbox]")
    .button({ icons: { primary: "ui-icon-circle-close"} })
    .click(function () {
        if (this.checked) {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-check' })
        }
        else {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-close' })
        }
    });
    $("input[type=checkbox]:checked")
    .button({ icons: { primary: "ui-icon-circle-check"} })
    .click(function () {
        if (this.checked) {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-check' })
        }
        else {
            $(this).button("option", "icons", { primary: 'ui-icon-circle-close' })
        }
    });
});
like image 909
Oundless Avatar asked Nov 04 '10 12:11

Oundless


2 Answers

This option ought to be part of jqueryui.

You could simplify with this:

$("input:checkbox")
    .button({
        icons: {primary: "ui-icon-circle-close"}
    })
    .click(function () {
        if (this.checked) {
            $(this).button("option", "icons", {primary: "ui-icon-circle-check"})
        }
        else {
            $(this).button("option", "icons", {primary: "ui-icon-circle-close"})
        }
    })
    .filter(":checked").button({icons: {primary: "ui-icon-circle-check"}});
like image 112
hoju Avatar answered Nov 12 '22 02:11

hoju


You can do this more easily using CSS. Just place the following in your style sheet (must be loaded after the jquery-ui.css):

input:checkbox + label .ui-icon {
    background-position: -32px -192px; /* position for ui-icon-circle-close */
}

input:checkbox:checked + label .ui-icon {
    background-position: -208px -192px; /* position for ui-icon-circle-check */
}
like image 1
Lisa DeBruine Avatar answered Nov 12 '22 02:11

Lisa DeBruine