Reputation: 14922
I have a table with 5 columns where I need the user to "select" and "unselect" cells. Then, I need to have a running total kept of how many cells in each COLUMN as "selected".
I am selecting the cells with a simple toggle function, changing the class of the cell
$('td').toggle(function() {
$(this).addClass("selectedCell");
}, function() {
$(this).removeClass("selectedCell");
});
So I suppose what I need to do is get all the cells in each column whose current class is "selectedCell" and assign it to a 5 variables so I can display "you selected 3 items from column 4" (for example).
How would I best accomplish this?
Upvotes: 0
Views: 995
Reputation: 78006
Not sure how your table is setup to handle 'columns' but to get a total of selected cells in the table, use this:
$('table').find('td.selectedCell').length
Example: http://jsfiddle.net/AlienWebguy/tYT2E/
If you changed your table setup to a div structure, it would be much easier to calculate what you need:
HTML:
<div id="wrapper">
<div class="column">
<div class="selectedCell">1</div>
<div>2</div>
<div class="selectedCell">3</div>
<div class="selectedCell">4</div>
<div>5</div>
<div>6</div>
<div class="selectedCell">7</div>
</div>
<div class="column">
<div class="selectedCell">8</div>
<div class="selectedCell">9</div>
<div>10</div>
..........
</div>
</div>
<div id="status"></div>
JQuery:
function update_counts(){
$('#status').html('');
$('.column').each(function(index){
$('#status').append($(this).find('.selectedCell').length + ' selected cells in column ' + (index + 1) + '<br />');
});
}
$('.column div').click(function(){
// Add or remove class
$(this).toggleClass('selectedCell');
// Update the class counts
update_counts();
});
// Run the function on domready
$(function(){
update_counts();
});
Example: http://jsfiddle.net/AlienWebguy/tYT2E/4/
Upvotes: 4