code messier than it should be
I have groups of check boxes.
When a checkbox is ticked/unticked i want to check if any check boxes in the same group are checked.
I have the following HTML, this is dynamically generated so there could be any number of 'groups'
- <div class="group">
- <span class="title--bold">Time Found</span>
- <span><input type="checkbox" name="vehicle" value="Bike"> Today</span>
- <span><input type="checkbox" name="vehicle" value="Bike"> Yesterday</span>
- <span><input type="checkbox" name="vehicle" value="Bike"> Last week</span>
- <span><input type="checkbox" name="vehicle" value="Bike"> Never</span>
- </div>
- <div class="group">
- <span class="title--bold">Animal Type</span>
- <span><input type="checkbox" name="vehicle" value="Bike">Cats</span>
- <span><input type="checkbox" name="vehicle" value="Bike">Dogs</span>
- </div>
And this is my javascript
- $(document).ready(function () {
-
- $("input[type=checkbox]").on("click" ,function () {
- console.log('mek');
- var n = 0;
- var rows = $(this).parent().parent().children('span');
-
- rows.each(function () {
- l = $(this).children('input:checked').length;
- n = n + l;
- });
- console.log(n);
- });
- });
To me it seams to be messier than it should be
What it does is find the .
group element which the target input element belongs to and then counts the children which match the 'input:checked' selector.
Due to the fact that each 'input' is nested inside a 'span' (and so is not a direct child of .group using .parent().parent() is necessary to get the .group
Due to the fact that once we have .group the elements i am interested in are not direct children it is nessesary to use .each()
And i have also had to store the matches in 'n' instead of using .length.
Is there any way this can be made shorter?
Perhaps the row "
var rows = $(this).parent().parent().children('span');" could become something like "
var rows = $(this).parent().siblings()
"
Is there any way the .each() can be removed?
Is there any way .length can be used instead of a counter (without removing the span tags)?