table row record click retrieve

how can i retrieve the first column in input box by clicking 1 row using j query? i already have a css style to hover the table row.

<script>
    $(document).ready(function(){
        $("#record tr").click(data);
    });
</script>
<table id="record">
    <tr>
        <TD>1</TD>
        <td>apple</td>
    </tr>
    <tr>
        <TD>2</TD>
        <TD>banana</TD>
    </tr>
    <tr>
        <TD>3</TD>
        <TD>orange</TD>
    </tr>
</table>

 <input type="text" name="input_1">
   

Upvotes: 1

Views: 41

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Get text content using text() with callback, there you can get index and value as argument. Now get input element using index for that eq() will help and at last update value using val().

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $("#record tr").click(function() {
      $('td', this).text(function(i, v) {
        $("#insert_here input").eq(i).val(v);
      });
    });
  });
</script>
<table id="record">
  <tr>
    <TD>apple</TD>
    <td>apple</td>
  </tr>
  <tr>
    <TD>banana</TD>
    <TD>banana</TD>
  </tr>
  <tr>
    <TD>orange</TD>
    <TD>orange</TD>
  </tr>
</table>




<div id="insert_here">
  <input type="text" name="input 1">
  <input type="text" name="input 2">
</div>


Or the same can be done using val() with callback

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
    $("#record tr").click(function() {
      var $td = $('td', this);
      $("#insert_here input").val(function(i) {
        return $td.eq(i).text();
      });
    });
  });
</script>
<table id="record">
  <tr>
    <TD>apple</TD>
    <td>apple</td>
  </tr>
  <tr>
    <TD>banana</TD>
    <TD>banana</TD>
  </tr>
  <tr>
    <TD>orange</TD>
    <TD>orange</TD>
  </tr>
</table>




<div id="insert_here">
  <input type="text" name="input 1">
  <input type="text" name="input 2">
</div>

Upvotes: 1

Related Questions