JQuery - Style checkbox, replace with image

I need this script to hide my checkboxes and place an image of a stylized checkbox instead. It correctly hides it and shows the default image, but it will not update the checkbox to check or uncheck the box when I click on it and not refresh the image. I guess this is a simple thing that I am missing, I'm still new to jQuery.

Here is the script:

        $(".check").each(function() {
            $(this).hide();

            var $image = $("<img src='assets/images/layout/checkbox/unchecked.png' />").insertAfter(this);    

            $image.click(function() {
                var $checkbox = $(this).prev(".check");
                $checkbox.prop('checked', !$checkbox.prop('checked'));

                if($checkbox.prop("checked")) {
                    $image.attr("src", "assets/images/layout/checkbox/checked.png");
                } else {
                    $image.attr("src", "assets/images/layout/checkbox/unchecked.png");
                }
            })
        });

Here is the HTML:

<input type="checkbox" class="check" />

Edit: Also, is this usually the best approach to styles? I cannot find anything that is much simpler than this, so any suggestions are appreciated.

+5
source share
4 answers

, jQuery, . 1.7.2, , .

+2

jQuery Zebra_Transform, , , (3 ) .

0

I tried several solutions and the best choice seems to be: http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ This just works fine.

0
source

Know that this is an older stream, but you need a solution to convert checkboxes to images - and that was the best answer. :) So we reorganized it and wanted to share it.

function setCheckboxImageSrc(checkbox, image, checkedUrl, uncheckedUrl) {
    if (checkbox.is(":checked")) {
        image.attr("src", checkedUrl);
    } else {
        image.attr("src", uncheckedUrl);
    }
}

function setCheckboxImage(checkboxObj, className, checkedUrl, uncheckedUrl) {
    checkboxObj.hide();

    var $image = $("<img src='" + checkedUrl + "' />").insertAfter(checkboxObj);
    setCheckboxImageSrc(checkboxObj, $image, checkedUrl, uncheckedUrl);

    $image.click(function () {
        var $checkbox = $image.prev("." + className);
        $checkbox.click();
        setCheckboxImageSrc($checkbox, $image, checkedUrl, uncheckedUrl);
    });
}

$(".checkboxUp").each(function () {
    setCheckboxImage($(this), "checkboxUp", "../../../images/DirectionUpChecked.png", "../../../images/DirectionUpUnchecked.png");
});

$(".checkboxDown").each(function () {
    setCheckboxImage($(this), "checkboxDown", "../../../images/DirectionDownChecked.png", "../../../images/DirectionDownUnchecked.png");
});
0
source

All Articles