Using jQuery, how would you figure out how many columns are in a table?
<script> alert($('table').columnCount()); </script> <table> <tr> <td>spans one column</td> <td colspan="2">spans two columns</td> <td colspan="3">spans three columns</td> <tr> </table>
The total number of columns in this example is 6. How could I determine this using jQuery?
Answer: Use the length Property You can simply use the length property to count or find the number of rows in an HTML table using jQuery. This property can be used to get the number of elements in any jQuery object.
columnCount = function() { return $('th', $(this). find('tbody')). length; }; var rowctr = $('#table1'). rowCount(); var colctr = $('#table1').
jQuery(". dname"). find("tr td:eq(1)"). val();
Here you go:
jsFiddle
$(function() { var colCount = 0; $('tr:nth-child(1) td').each(function () { if ($(this).attr('colspan')) { colCount += +$(this).attr('colspan'); } else { colCount++; } }); });
$("table").find("tr:first td").length;
I edited as I didn't realize you were counting the colspan's.
If you want to include using colspan try a loop through the td's in the first row:
var cols = $("table").find("tr:first td"); var count = 0; for(var i = 0; i < cols.length; i++) { var colspan = cols.eq(i).attr("colspan"); if( colspan && colspan > 1) { count += colspan; }else{ count++; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With