Sideshow
Sideshow

Reputation: 1351

JQuery populate form fields with data from a selected table row

I have a simple table with an edit button at the end of each row as below:

<table class='document_table'>
<tr>
    <td>Item1</td>
    <td>Item2</td>
    <td>Item3</td>
    <td><a href='javascript:void(0);' class='edit_doc'>Edit</a></td>
</tr>
<tr>
    <td colspan='4'>Item4</td>
</tr>
<tr>
    <td colspan='4'>Item5</td>
</tr>
<tr>
    <td>Item1</td>
    <td>Item2</td>
    <td>Item3</td>
    <td><a href='javascript:void(0);' class='edit_doc'>Edit</a></td>
</tr>
<tr>
    <td colspan='4'>Item4</td>
</tr>
<tr>
    <td colspan='4'>Item5</td>
</tr>
</table>

What I need to do is when the edit button is clicked is populate a form with the data from the three rows. Note that the number of rows is dynamic.

Form html is as follows:

 <label>Input 1<label>
 <input type='text' class='input1' />
 <label>Input 2<label>
 <input type='text' class='input2' />
 <label>Input 3<label>
 <input type='text' class='input3' />...etc

So far my jQuery is as follows but is not working....

var row1=$(this).closest('tr').find('td').eq(0).val();
$('.input1').val(row1);

I also have to be alble to get the values from the next two rows :(

Upvotes: 2

Views: 3555

Answers (1)

You should use .html() instead of .val() , like this:

var row1=$(this).closest('tr').find('td').eq(0).html();

To obtain your other rows, you could do:

var td = $(this).closest('tr').find('td');
var row1 = td.eq(0).html();
var row2 = td.eq(1).html();
var row3 = td.eq(2).html();

Upvotes: 4

Related Questions