w3resource

jQuery: Count number of rows and columns in a table

jQuery Practical exercise Part - I : Exercise-23

Count number of rows and columns in a table using jQuery.

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-git.js"></script>
 <meta charset="utf-8">
 <meta name="viewport" content="width=device-width">
 <title>Count number of rows and columns in a table using jQuery.</title>
 </head>
 <body>
 <table id="table1">
  <tr>
   <th>Tools</th>
    <th>Description</th>
	</tr>
	<tr>
	<td>phpMyAdmin</td>
	<td>Third party, Free, Web based </td>
	</tr>
	<tr>
	<td>HeidiSQL</td>
	<td>Third party, Free, For Windows </td>
	</tr>
	<tr>
	<td>Adminer</td>
	<td>Third party, Free</td>
	</tr>
	<tr>
	<td>DBEdit </td>
	<td>Third party, Free</td>
	</tr>
	<tr>
	<td>dbForge GUI Tools</td>
	 <td>Third party, Free</td>
	 </tr>
	 <tr>
	 <td> Navicat </td>
	 <td>Third party, Commercial </td>
	 </tr>
	 <tr>
	 <td>Maatkit</td>
	 <td>Third party, Command line, free </td>
	 </tr>
	 <tr>
	 <td>MySQL Sandbox</td>
	 <td>Third party, Command line, free</td>
	 </tr>
	 <tr>
	 <td>SQLBuddy </td>
	 <td> A free Web-based front end, developed in PHP.</td>
	 </tr>
	 <tr>
	 <td>SQLyog </td>
	 <td>Commercial, but a free 'community' edition is available.</td>
	 </tr>
	 <tr>
	  <td>Toad for MySQL </td>
	  <td>Third party, free  from Quest Software</td>
	 </tr>
</table>
 </body>
</html>

JavaScript Code:

$.fn.rowCount = function() {
    return $('tr', $(this).find('tbody')).length;
};

$.fn.columnCount = function() {
    return $('th', $(this).find('tbody')).length;
};
var

rowctr = $('#table1').rowCount();
var colctr = $('#table1').columnCount();

console.log('No of Rows:'+rowctr);
console.log('No of Columns:'+colctr);

See the Pen jquery-practical-exercise-23 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Count number of rows and columns in a table using jQuery.
Next: How to get textarea text using jQuery.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.