leora
leora

Reputation: 196539

How can I get the value of a textbox in the current HTML table row?

I have the following HTML table:

<table>
   <tr>
       <th>Name</th>
       <th>Button</th>
   </tr>
   <tr>
         <td><input type='text' name='Name' id='Name' class='NameClass' /></td>
         <td><a id="myLink" >Click Here</a></td>
   </tr>
</table>

I am simplifying that table because there are many columns and rows but basically when I click on the link, I want to read in the value of whatever is in the Name textbox into a local variable (for simplification we can just alert the value).

What is the best way using jQuery to read the value of that textbox? I want to avoid any hard-coded column offsets, as although it's the first column in this example, it's possible I will add new columns, so I want to make it a bit more future-proof.

Upvotes: 0

Views: 16486

Answers (2)

Muhammad Haseeb Khan
Muhammad Haseeb Khan

Reputation: 895

Another option

var result= $(this).parent().parent().find('input[type="text"]').val();

If Another input box is added then use the class name of input for which value to required

var result= $(this).parent().parent().find('.className').val();

Upvotes: -1

Ram
Ram

Reputation: 144689

IDs are supposed to be unique, you can use classes instead, after changing IDs to classes you can code:

$('.myLink').click(function(e){
   e.preventDefault();
   var val = $(this).closest('tr').find('.NameClass').val();
   // var val = $(this).parent().prev().find('.NameClass').val();
});

Upvotes: 5

Related Questions