In this article I will explain with an example, how to get selected (checked)
CheckBox Row (Cell) values of
HTML Table using
JavaScript.
When the Button is clicked, all the
CheckBoxes inside the
HTML Table will be referenced and then the Row (Cell) values of selected (checked)
CheckBoxes will be extracted and displayed using
JavaScript Alert Message Box.
HTML Markup
The following
HTML Markup consists of an
Html Table and a
Button. The Button has been assigned an
OnClick event which calls a
JavaScript function.
<table cellspacing="0" rules="all" border="1" id="Table1" style="border-collapse:collapse;">
<tr>
<th> </th>
<th style="width:80px">Customer Id</th>
<th style="width:120px">Name</th>
<th style="width:120px">Country</th>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>1</td>
<td>John Hammond</td>
<td>United States</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>2</td>
<td>Mudassar Khan</td>
<td>India</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>3</td>
<td>Suzanne Mathews</td>
<td>France</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>4</td>
<td>Robert Schidner</td>
<td>Russia</td>
</tr>
</table>
<br />
<input type="button" value="Get Selected" onclick="GetSelected()" />
JavaScript function to get selected (checked) CheckBox Row values of Html Table
Inside the
GetSelected JavaScript function, first the Html Table is referenced and then all the
CheckBoxes inside the Html Table are referenced.
Then a loop is executed over the
CheckBoxes and if the
CheckBox is checked, the values of
Cells of the Row are extracted and displayed using
JavaScript Alert Message Box.
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table1");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "Id Name Country\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += row.cells[1].innerHTML;
message += " " + row.cells[2].innerHTML;
message += " " + row.cells[3].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads