Learning Horizon | For Learners

ASP.NET, SQL SERVER, JQUERY,JAVASCRIPT, WEBSPHERE

Thursday 27 September 2012

Get Value Of "td" When Checkbox In Adjacent "td" Is Checked | Jquery

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.

5 comments:

  1. thanks for this write up

    ReplyDelete
  2. thank you... im too late just starting to learn JQUERY...

    ReplyDelete
  3. Exactly what I want. Thank you!

    ReplyDelete
  4. Exactly what I want. Thank you!

    ReplyDelete

Please do not enter spam links.