Scrolling through CSS tables and counting selected cells
I am trying to loop through the entire css table and show how many cells are selected in each one.
I use every method but it doesn't work.
Thanks for any help.
My code is below and this is fiddle
JQuery
$(function () {
$('.css-table-td').click(function () {
var theTable = $(this).closest('.css-table');
$(this).toggleClass("highligh-cell");
});
});
$("#csstableinfo").click( function() {
var sCount=0;
$(".css-table div").each(function (index) {
// sCount=theTable.find('.css-table-td.highligh-cell').length; this is not workikng
alert (sCount)
});
});
Html:
<div class="css-table">
<div class="css-table-tr">
<div class="css-table-td" id="1">b</div>
<div class="css-table-td" id="2">c</div>
<div class="css-table-td" id="3">e</div>
</div>
</div>
<br/>
<div class="css-table">
<div class="css-table-tr">
<div class="css-table-td" id="1">b</div>
<div class="css-table-td" id="2">c</div>
<div class="css-table-td" id="3">e</div>
</div>
</div>
<br/>
<div class="css-table">
<div class="css-table-tr">
<div class="css-table-td" id="1">b</div>
<div class="css-table-td" id="2">c</div>
<div class="css-table-td" id="3">e</div>
</div>
</div>
<br/>
<INPUT TYPE="submit" id="csstableinfo" VALUE="Count Selected">
CSS
.css-table {
display: table;
background-color:#ccc;
}
.css-table-tr {
display: table-row;
height:30px;
}
.css-table-td {
display: table-cell;
border:1px solid #fff;
width: 30px;
text-align:center;
vertical-align:middle;
}
.highligh-cell {
background: #999;
}
source to share
$(".css-table .highligh-cell").length
will give you the number of selected items, no need to use them.
$("#csstableinfo").click(function () {
alert($(".css-table .highligh-cell").length);
});
EDIT:
To find out how many are selected in each table:
$("#csstableinfo").click(function () {
var msg = "";
$(".css-table").each(function(index) {
var sCount = $(this).find('.highligh-cell').length;
msg += "table_" + index + " = " + sCount + "\n";
});
alert(msg);
});
source to share
Do you even get a bunch of warnings? if not, the problem is with the $ (". css-table div") call. You shouldn't call it like that because every div you call already contains a css table class.
try using $ (". css-table"), if it doesn't work better work with IDs.
PS you also use different classes for each row, so they won't identify the rows.
source to share
You just need to increment the counter and do each for the selected ie class .highligh-cell
:
$("#csstableinfo").click( function() {
var sCount=0;
$(".highligh-cell").each(function (index) {
// sCount=theTable.find('.css-table-td.highligh-cell').length;
sCount++;
});
alert (sCount)
});
Checkout DEMO
source to share