Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Creating a Image Toggle for a checkbox

Tags:

jquery

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?

like image 241
AnApprentice Avatar asked Dec 30 '10 04:12

AnApprentice


2 Answers

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

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

$('#myImage').click(function() {
    cbox.checked = !cbox.checked;
});
like image 129
user113716 Avatar answered Oct 11 '22 22:10

user113716


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");
   }
});
like image 22
karim79 Avatar answered Oct 11 '22 21:10

karim79