Reputation: 8366
I have a Table as follows.. I need to Display Table Cell Content If corresponding Checkbox is checked on button Click
For eg:
If Row2 is checked, alert box should say Row2
Here is my code,
JavaScript:
<script type="text/javascript">
function whichRow(tableID){
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount-1; i++) {
var cell_val=table.rows[i].cells[1].innerHTML;
alert(cell_val);
}
}
</script>
HTML:
<table id="Item1">
<tr><td>Row 1</td><td><input name="rowno" type="checkbox"/></td></tr>
<tr><td>Row 2</td><td><input name="rowno" type="checkbox"/></td></tr>
<tr><td>Row 3</td><td><input name="rowno" type="checkbox" /></td></tr>
<tr>
<td colspan="2"><input type="submit" name="button" id="button" value="Submit" onclick="whichRow('Item1')" /></td>
</tr>
</table>
Problem that I am facing:
Currently I am able to retrieve innerHTML of checkbox but unable to find out whether its checked or not...
Upvotes: 1
Views: 1912
Reputation: 89770
If I understood your question correctly, you can try it this way.
EDIT Updated based on comments
function whichRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var inputBoxes = table.getElementsByTagName('input'); //modified to get only input tags present within the table
for (var i = 0; i < rowCount - 1; i++) {
if (inputBoxes[i].checked) { //checks if the checkbox is selected
var cell_val = table.rows[i].cells[0].innerHTML;
alert(cell_val);
}
}
}
Upvotes: 2
Reputation: 388406
Without jQuery
function whichRow(tableID){
var table = document.getElementById(tableID), inpt, chks;
//if querySelectorAll is present use it else fallback gracefully
if(table.querySelectorAll){
chks = table.querySelectorAll('input[name=rowno]');
} else {
var temp = table.getElementsByTagName('input');
chks = [];
for(var i=0; i < temp.length; i++) {
inpt = temp[i];
if(inpt.name == 'rowno'){
chks.push(inpt);
}
}
}
for(var i=0; i < chks.length; i++) {
inpt = chks[i];
if(inpt.name == 'rowno' && inpt.checked){
alert(chks[i].parentNode.previousSibling.innerHTML)
}
}
}
Demo: Fiddle
With jQuery - Cross Browser
function whichRow(tableID){
$('#' + tableID).find('input[name="rowno"]:checked').each(function(){
alert($(this).closest('td').prev().text())
})
}
Demo: Fiddle
Upvotes: 1
Reputation: 99534
Here is the jQuery version. In this case, there's no need to pass the parent table id
through the onclick
event handler.
$('#button').on('click', function() {
var selected = $(this).parents('table')
.find('input[type=checkbox]:checked').map(function() {
return $.trim($(this).parent().prev('td').text());
}).get().join();
// Remove the .join() method to get the array instead
console.log(selected);
});
Upvotes: 1