mardi 6 janvier 2015

Jquery show div if ANY of checkboxes with same target is checked, otherwise hide the div

I have a form with checkboxes which each have 'data-target' attribute to select a hidden div to show when checked.



<input type="checkbox" name="group[]" class="show-div" data-target="div-1" value="1">
<input type="checkbox" name="group[]" class="show-div" data-target="div-2" value="2">
<input type="checkbox" name="group[]" class="show-div" data-target="div-2" value="3">
<input type="checkbox" name="group[]" class="show-div" data-target="div-2" value="4">

<div id="div-1" class="hidden"></div>
<div id="div-2" class="hidden"></div>


The javascript is as follows:



$('input.show-div').on('change', function() {
var source = $(this);
var target = $('#' + source.attr('data-target'));
if (this.checked) target.show();
else target.hide();
});


This works obviously with the first checkbox or if check/uncheck only one of the last three. What I'd like to achieve is that if any of the checkboxes with same target div is checked, then show it, otherwise hide it.





Aucun commentaire:

Enregistrer un commentaire