Sid
Sid

Reputation: 5833

Pre-populating the select dropdown with the selected table row

I have a table structure like this

Fruit         Price        Qty
Apple          30          10
Orange         20          20
Grapes         12          10
pineapple      10           5

Now when I select any row from this table, I want to pre-set the corresponding value in select dropdown.

For e.g if I select Apple from the table, I need to pre-set the corresponding values of the selected row from table in select statement i.e Fruit = Apple, Price = 30 and Qty = 10 in my corresponding select statement.

How can I do that?

Upvotes: 2

Views: 446

Answers (2)

Pugazh
Pugazh

Reputation: 9561

Try this

$(function() {
  $('tr').click(function() {
    var sid = 0;
    $(this).find('td').each(function() {
      sid++;
      $('#s' + sid).val($(this).text());
    });
  });
});
table {
  border-collapse: collapse;
}
tr,
td {
  border: 1px solid grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Fruit</td>
    <td>Price</td>
    <td>Qty</td>
  </tr>
  <tr>
    <td>Apple</td>
    <td>30</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Orange</td>
    <td>20</td>
    <td>20</td>
  </tr>
  <tr>
    <td>Grapes</td>
    <td>12</td>
    <td>10</td>
  </tr>
  <tr>
    <td>Pineapple</td>
    <td>10</td>
    <td>5</td>
  </tr>
</table>
<br/>Fruit:
<select id="s1">
  <option>--Select--</option>
  <option>Apple</option>
  <option>Orange</option>
  <option>Grapes</option>
  <option>Pineapple</option>
</select>
<br/>Price:
<select id="s2">
  <option>--Select--</option>
  <option>30</option>
  <option>20</option>
  <option>12</option>
  <option>10</option>
</select>
<br/>Qty:
<select id="s3">
  <option>--Select--</option>
  <option>10</option>
  <option>20</option>
  <option>10</option>
  <option>5</option>
</select>

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

DEMO HERE

Assuming your html to be as below:

    <table class="fruits">
    <thead>
        <th>Fruit</th>
        <th>Price</th>
        <th>Qty</th>
    </thead>
    <tbody>
        <tr>
            <td>Apple</td>
            <td>30</td>
            <td>10</td>
        </tr>
        <tr>
            <td>Orange</td>
            <td>20</td>
            <td>20</td>
        </tr>
        <tr>
            <td>Grapes</td>
            <td>12</td>
            <td>10</td>
        </tr>
        <tr>
            <td>Pineapple</td>
            <td>10</td>
            <td>5</td>
        </tr>
    </tbody>
</table>

JS

$('.fruits tr').on('click',function(){
    var fruit = $(this).find('td:first-child').text().trim();
    var price=$(this).find('td:nth-child(2)').text().trim();
    var qty=$(this).find('td:last-child').text().trim();
    alert("Fruit =" + fruit+", Price =" + price +", Qty = "+qty);

    //Can use those values and pass as parameter to your select statement
});

Upvotes: 1

Related Questions