开发者

jQuery - Creating a Image Toggle for a checkbox

I have a checkbox which is开发者_开发知识库 pretty simple, it's a boolean, true/false, checked or unchecked.

What I would like to do is keep the checkbox but hide it and allow the user to click on an image (a dark circle or a blue circle) which would then toggle the checkbox on/off. But I can't figure out where to start on something like this.

Ideas?


Example: http://jsfiddle.net/Gfmz2/ (checkbox is visible in the example)

var cbox = $('#myHiddenCheckbox')[0];

$('#myImage').click(function() {
    cbox.checked = !cbox.checked;
});


You can put the image into the checkbox's label, which effectively makes it part of the checkbox (so clicking on it will toggle the checkbox):

<label for="moreinfo">
<img src="darkCircle.jpg"/>
<input name="moreinfo" type="checkbox" id="moreinfo" style="display:none">
</label>

$("#moreinfo").change(function() {
   if(this.checked) {
       $(this).prev().attr("src", "lightCircle.jpg");
   } else {
       $(this).prev().attr("src", "darkCircle.jpg");
   }
});


In addition to what Patrick suggested you can add the image toggling code as below:

var cbox = $('#myHiddenCheckbox')[0];

$('#myImage').click(function() {
    cbox.checked = !cbox.checked;
        this.src = (cbox.checked)?"images/bluecircle.jpg":"images/blackcircle.jpg";
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜