jQuery: get table cell values 

Joined:
02/21/2009
Posts:
151

March 29, 2011 11:25:35    Last update: March 29, 2011 11:25:35
With jQuery, it is pretty easy to access a table cell: just use the $('table tr:eq('+row+') td:eq('+column+')') selector. Below is a test page:
  • Code
  • Demo
<!DOCTYPE html>
<html>
<head>
	<title>jQuery Table</title>

	<style type="text/css">
	body {
		font-family: sans-serif;
	}

	table {
		border-collapse: collapse;
		margin-bottom: 5px;
	}

	td {
		padding: 4px;
		border: #4488aa 1px solid;
	}

	input {
		text-align: right;
		padding: 2px;
		width: 20px;
	}
	</style>

	<script type="text/javascript" 
		src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
	</script>

	<script type="text/javascript">
	$(function() {
		$('button').click(function() {
			var row = $('input:first').val();
			var column = $('input:eq(1)').val();
			var cell = $('table tr:eq('+row+') td:eq('+column+')');
			if (cell.length == 0) {
				$('#value').text('Undefined');
			}
			else {
				$('#value').text(cell.text());
			}
		});
	});
	</script>
</head>

<body>
	<h1>Table Cell Value</h1>
	<table>
		<tr><td>Cell 1-1</td><td>Cell 1-2</td><td>Cell 1-3</td></tr>
		<tr><td>Cell 2-1</td><td>Cell 2-2</td><td>Cell 2-3</td></tr>
		<tr><td>Cell 3-1</td><td>Cell 3-2</td><td>Cell 3-3</td></tr>
	</table>

	Row: <input type="text" value="0">
	Column: <input type="text" value="0">
	Value: <span id="value">?</span><br>
	<button>Get Value</button>
</body>
</html>
Share |
| Comment  | Tags