samedi 4 avril 2015

How to show/hide a specific image based on which checkbox is clicked (clicking cbox3 should open tinypic3)

I have 10 different checkboxes, each with their unique ID - in sequential order like: cbox1, cbox2, etc.. Each checkbox has an associated "tinybox" div which contains an image, and each image has an ID also in sequential order, like tinypic1, tinypic2, etc.. I'm trying to write a jQuery script so that when a user clicks on any of the checkboxes, it will then either .show() or .hide() that associated tinypic.


For example, let's say a user clicks on the third checkbox, which has id="cbox3", the script should identify this is cbox THREE and therefore show or hide "tinypic3". Each checkbox has a unique ID, but has the same Class (called cboxes).


This jQuery script successfully uses the class to run when any cbox is clicked, but how do I get it to show/hide the associated TINYPIC instead of show/hiding the cbox itself?



<script type="text/javascript">
$(document).ready(function() {
$('.cboxes').click(function() {
if ($(this).prop('checked')) {
$(this).next().show(); // This should show the associated tinypic with the same number as the cbox that was clicked.
}
else {
$(this).next().hide(); // This should hide the associated tinypic with the same number as the cbox that was clicked.
}
});
});
</script>


I've tried substituting $(this).next().show(); for $("[id^='tinypic']").show(); or $('input:checkbox[id^="tinypic_"]') but it won't work. I'm obviously not understanding the logic somehow.


Any help is huge! Thanks a lot :)


Here's a sample checkbox for cbox2:



<li>
<input id="cbox2" type="checkbox" name="cbox2" class="cboxes" />
<label for="cbox2">Show</label>
<div class="tinybox">
<img src="http://ift.tt/1a8Yg1g" alt="tinypic2" id="tinypic2" style="display:none;">
</div>
</li>




Aucun commentaire:

Enregistrer un commentaire