开发者

Checking a checkbox by clicking an image

开发者 https://www.devze.com 2023-02-02 20:29 出处:网络
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

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 i开发者_运维技巧n javascript. Thanks.


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.


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.


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;  
}


As they answered above you don't need to do it through javascript, if you are curious about how to attach an event handler to the image. You do need to change the checkbox id to something other than what the image id is. I renamed it to chk2

document.getElementById('img2').onclick = function () //attach to onclick
{                             
        var checkbox = document.getElementById('chk2'); //find checkbox

        checkbox.checked = !checkbox.checked; //toggle the checked status
}
0

精彩评论

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

关注公众号