vendredi 9 janvier 2015

How can i improve this jquery / js checkbox code

I've been having a hard time figuring this codes out.


The checkbox codes functions like this:


There is a global checkbox (Check all) and there are child (Single) checkboxes. If the (global) checkbox is checked, all the (child) checkboxes will be checked as well, a div will show, and if the global is unchecked, it un-checks the (child) checkboxes and the div will hide (jquery hide and show). The the numbers of the checked checkboxes will be displayed.


This is the problem; is if a child checkbox is unchecked, the global checkbox still remains checked and if all the child checkboxes are checked, the global checkbox should be checked immidiately as well.



<script src="http://ift.tt/1qRgvOJ"> </script>
<div id="mydiv" style="display:none;">RESTORE | DELETE
<span>Checked: </span>
<span id="counter"></span>
</div>
<input type="checkbox" id="global">
<br>
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">
<input type="checkbox" class="child">

$(document).ready(function() {
$('#global').click(function() {
$('.child').prop('checked', $(this).is(':checked'));

if ($(this).is(':checked'))
$('#mydiv').show();
else
$('#mydiv').hide();

count();
});

$('.child').change(function() {
var checkedLength = $('.child:checked').length;
if (checkedLength > 0)
$('#mydiv').show();
else
$('#mydiv').hide();
count();
});
});

var count = function() {
var i = $('input.child:checked').length;
$('#counter').html(i);
}


All support are apreciated. Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire