views:

84

answers:

1

Hi, I have a small form which takes the values name (TextBox), age(textbox) , Education(select box with values"Bachelors" and "Masters"). So I have a Button with the "ADD" which adds the values to database and displays it in a table format.

Iam having the table with 10 rows and each row is identified . So I have two Buttons such as select and Cancel

When We say select the Values in the table should go their Respective boxes name value should go to name box and Age Value should go their age box and so on..

How can i acheive this using Jquery

+1  A: 

For HTML like this:

...
<div>
    <label for="NameTextBox">Name:</label> 
    <input type="text" id="NameTextBox" />
</div>
<div>
    <label for="AgeTextBox">Age:</label> 
    <input type="text" id="AgeTextBox" />
</div>
<div>
    <label for="EducationSelect">Education:</label>
    <select id="EducationSelect">
        <option value="Bachelors">Bachelors</option>
        <option value="Masters">Masters</option>
    </select>
</div>
<input type="button" value="Add" />

<table>
  <tr>
    <th></th>
    <th>Name</th>
    <th>Age</th>
    <th>Education</th>
  </tr>
  <tr>
    <td><input type="button" id="row1" value="Select" /></td>
    <td>Name1</td>
    <td>44</td>
    <td>Bachelors</td>
  </tr>
  <tr>
     <td><input type="button" id="row2" value="Select" /></td>
     <td>Name2</td>
     <td>32</td>
     <td>Masters</td>
  </tr>
</table>
...

The following jQuery expression will copy the values from the selected row into the form on 'Select' button click:

$(function()
{
    $("table input").click(function(event) 
    {
      $("#NameTextBox").val($("tr").has("#" + event.target.id).find("td:nth-child(2)").html());
      $("#AgeTextBox").val($("tr").has("#" + event.target.id).find("td:nth-child(3)").html());
      $("#EducationSelect").val($("tr").has("#" + event.target.id).find("td:nth-child(4)").html());
    });
 });