Johns soronza
Johns soronza

Reputation: 23

Add css If checkbox checked?

Im using a data-attribute from an input checkbox to add a background image to the element #checkbox1 if the checkbox is checked.

What does I have to do with this function to hide the background image if the checkbox is not checked.

HTML

<div id="checkbox1"></div>

<input data-image="url(http://www.siwikultur.de/kulturpur/wp-content/uploads/2009/03/schneider.jpg)" type="checkbox" id="check1">
<label for="check1">USB-Stick-Halterung</label>

Jquery

<script> 
$('#check1').on('change', function () {
$("#checkbox1").css("background-image", ($('#check1:checked').data("image")));
});  
</script>

Upvotes: 2

Views: 939

Answers (1)

Marwelln
Marwelln

Reputation: 29413

Check if the button is checked with the checked property. If it is, display the image, if it's not, set background-image to none.

$('#check1').on('change', function () {
    $("#checkbox1").css("background-image", this.checked ? this.dataset.image : 'none');
}); 

Upvotes: 3

Related Questions