2

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>
1
  • If you could put the checkbox before your div you can do it with just CSS. Commented Feb 28, 2015 at 19:16

1 Answer 1

3

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');
}); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.