2

i have a image with checkbox, i used this code for Checking a checkbox by clicking an image...

<label for="img1"><img class="img" src="myimage.jpg" /></label>
<input type="checkbox" class="chk " checked="checked" id="img1" name="img1" value="0" />

its working fine, my question is, i want when checking check box above image opacity will be 0.5 or display a extra div over this image and when Un check above image opacity return to 1.0 or remove that div if we use div, any idea.???

thanks

mans
  • 1,087
  • 4
  • 26
  • 44
  • This has been answered here: http://stackoverflow.com/questions/5275857/highlight-label-if-checkbox-is-checked – aaaaaa Apr 01 '13 at 08:43

3 Answers3

6

You can accomplish this using some advanced CSS selectors provided that the <label> is the checkbox. The ~ selector is called general sibling selector and will match all sibling after the element.

jsFiddle

CSS

input:checked ~ label {
    opacity: 0.5;
}

HTML

<input type="checkbox" class="chk " checked="checked" id="img1" name="img1" value="0" />
<label for="img1">
    <img class="img" src="https://www.google.com.au/images/srpr/logo4w.png" />
</label>

Support

Support for :checked is only present for IE9 and above, if you need support for IE8 then you can you use a .checked class as use it in addition to the CSS3 :checked selector.

JS

$('#img1').click(function () {
    $(this).toggleClass('checked');
});

CSS

input:checked ~ label,
input.checked ~ label {
    opacity: 0.5;
}

For support < IE8 then you should use a more general JavaScript solution.

$('#img1').click(function () {
    $('label[for=' + this.id + ']').toggleClass('checked');
});

label.checked {
    opacity: 0.5;
}
Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • its working fine... one question this CSS property supported all major browsers...?? – mans Apr 01 '13 at 08:51
  • From IE9 and above, if you want support earlier than that it needs to be done with javascript. https://developer.mozilla.org/en/docs/CSS/:checked – Daniel Imms Apr 01 '13 at 08:53
1
$('.img').click(function() {
    if ($('#img1').is(':checked'))
        $(this).css('opacity', 0.5);
    else
        $(this).css('opacity', 1);
});
Jon P
  • 826
  • 1
  • 7
  • 20
0
$('.img').click(function() {
    $(this).css('opacity', $('#img1').is(':checked')?0.5:1.0);
});
  • Hello, welcome to StackOverflow. Good answers usually have some text explaining what the code is doing. That will help people who don't understand what you're doing. – carlosfigueira Jul 19 '13 at 21:15