Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a checkbox by clicking an image

Tags:

javascript

I have checkboxes under the thumbnails, here: http://jsfiddle.net/pAYFa/ I want to do that by clicking the thumbnail, checkbox gets checked. I think this can be done with javascript, I'll appriciate any help in javascript. Thanks.

like image 627
John Avatar asked Jan 07 '11 15:01

John


3 Answers

Just put the image into a label, and remove the duplicate IDs. I've done it for your first one: http://jsfiddle.net/karim79/pAYFa/1/

Each ID in the document must be unique as per the specification.

like image 156
karim79 Avatar answered Sep 18 '22 17:09

karim79


With jQuery this is child's play:

$('img').click(function(){
  $(this).next().click();
})

without, it becomes a little harder. I gave your checkboxes unique id's (img1_cb and img2_cb) and added a click handler to each image eg:

<img class="img" src="http://s5.tinypic.com/30v0ncn_th.jpg" id="img1" onclick="toggle('img1_cb')" />

Then the JavaScript was:

function toggle(what){
  var cb = document.getElementById(what);
  cb.checked = !cb.checked;  
}
like image 22
Jamiec Avatar answered Sep 21 '22 17:09

Jamiec


Well, the easiest way would be to put a label around your image. This will do exactly what you want:

<label for="img1"><img class="img" src="http://s5.tinypic.com/30v0ncn_th.jpg" /></label>
<input type="checkbox" class="chk " checked="checked" id="img1" name="img1" value="0" />

No javascript needed! You will have to remove your id="img1" from your <img> tag though, as you can't have more than one element with the same id.

like image 21
Spiny Norman Avatar answered Sep 21 '22 17:09

Spiny Norman