Today my friend needs help because he wants to get the value of <td> when the checkbox in the adjacent <td> is checked. So I decided to write a tutorial on it so that it will help other students especially beginners.
Take a simple example to demonstrate it.
Step 1: Make a table with 3 rows and 2 columns.
<table id="root" border="1" align="center">
<tr>
<td><input type="checkbox" /></td>
<td>First</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Second</td>
</tr>
<tr>
<td><input type="checkbox" /></td>
<td>Third</td>
</tr>
</table>
Step 2: Make an HTML button.
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
Step 3: Here is the Jquery code to get the checked checkbox and pick the adjacent <td> value.
$(document).ready(function(){
$("#firstButton").click(function(){
$('#root input[type="checkbox"]:checked').each(function(){
var getRow = $(this).parents('tr');
alert(getRow.find('td:eq(1)').html());
});
});
});
How it works
When you click on submit button(having id=firstButton) a function is called. [$('#root input[type="checkbox"]:checked').each(function()] this line checks the checked checkbox in a table (having id=root) by calling [each()](a built-in function). ‘getRow’ variable have got the ‘tr’ for which the checkbox is checked and finally this line[ getRow.find('td:eq(1)').html() ] get the adjacent <td> value.
If you don’t want to do it on a submit button click then simply replace the [$("#firstButton").click(function(){ ]
by
[ $('input[type="checkbox"]').change(function() { ]
and you will get the value of adjacent <td> when you just check the checkbox.
Very good. Thanks very much.
ReplyDeletethanks for this write up
ReplyDeletethank you... im too late just starting to learn JQUERY...
ReplyDeleteExactly what I want. Thank you!
ReplyDeleteExactly what I want. Thank you!
ReplyDelete