Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Style checkbox, replace with image

Tags:

html

jquery

css

I need this script to hide my checkboxes and put an image of a styled checkbox in place of it. It is properly hiding it and showing the default image, but it will not update the checkbox to checked or unchecked once I click on it, nor will it update the image. I'm assuming it's a simple thing I am overlooking, 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 generally the best approach to styling checkboxes? I can't seem to find anything that is much easier than this, so any suggestions are appreciated.

like image 667
ohiock Avatar asked Nov 03 '22 21:11

ohiock


1 Answers

It turns out I was using a dated version of jQuery, which was the problem. I updated to 1.7.2 and everything worked as it should.

like image 95
ohiock Avatar answered Nov 08 '22 10:11

ohiock