Reputation: 788
I want to change the opacity of the checkbox image to 1.0 (normal opacity) once the checkbox is checked and the default opacity set to 0.5 (half opacity). But I have no idea about the coding in JavaScript and CSS.
<input type="checkbox" id="n1" name="n1" style="display: none;" /><label for="n1"><img src="images/n1.png" width="20" height="20" /></label>
<input type="checkbox" id="n2" name="n2" style="display: none;" /><label for="n2"><img src="images/n2.png" width="20" height="20" /></label>
...
<input type="checkbox" id="n50" name="n50" style="display: none;" /><label for="n2"><img src="images/n50.png" width="20" height="20" /></label>
Upvotes: 1
Views: 3910
Reputation: 22711
Can you try this,
$(document).ready(function(e) {
$('input:checkbox').click(function(){
var ImgId = 'img_'+$(this).attr('id');
if( $(this).is(':checked')) {
$("#"+ImgId).css('opacity', '0.5');
} else {
$("#"+ImgId).css('opacity', '1');
}
});//end click
});//end ready
HTML:
<input type="checkbox" id="n1" name="n1" /><label for="n1"><img src="images/n1.png" width="20" height="20" id='img_n1' /></label>
<input type="checkbox" id="n2" name="n2" /><label for="n2"><img src="images/n2.png" width="20" height="20" id='img_n2'/></label>
Upvotes: 0
Reputation: 150010
Here's a way to do it with no JS, just CSS:
label img {
opacity : 0.5;
}
input[type=checkbox]:checked + label img {
opacity : 1;
}
Demo: http://jsfiddle.net/W2hHg/
Note that it uses the adjacent sibling selector +
, so it relies on the label element immediately following the corresponding checkbox element.
But if you want to support IE<=8 which doesn't implement the CSS :checked
selector I would still suggest defining the label img
class above to set the default opacity, then define the following class for when checked:
label.checked img {
opacity : 1;
}
...and then add and remove that class using JS:
document.onclick = function(e) {
if (!e) e = window.event;
var el = e.target || e.srcElement;
if (el.type === "checkbox") {
if (el.checked)
el.nextSibling.className += " checked";
else
el.nextSibling.className = el.nextSibling.className.replace(/\bchecked\b/,"");
}
};
Demo: http://jsfiddle.net/W2hHg/2/
Upvotes: 1