Evan Root Evan Root - 5 months ago 7
Javascript Question

Unable to get data from the second column of a table on clicking of the button in third column

I have a table which has four columns second being a paragraph field , the third being an input field and fourth being a button . What i want is on clicking of the button row the data from the paragraph column should be applied to the input field i.e third row .

Its not possible to select every row using each function as every row is different and theres only few rows like this . How can this be done

I have tried this but it didn't work



var or1 = $("#tab_logic button");
or1.each(function() {
$(this).click(function(){
alert("u");
var u = $(this).parent("tr").find('td:first').html();
alert(u);
});
});




Answer

Without knowing the exact HTML, I made this based on your explanation. If I understand correctly, this is what you want to achieve?

$("button").click(function() {
	var row = $(this).closest("tr");
  var name = row.find("p").html();
  var input = row.find("input");
  input.val(name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead>
    <th>ID</th>
    <th>Name</th>
    <th>Input</th>
    <th>Button</th>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td><p>John Doe</p></td>
      <td><input type="text" placeholder="Name"/></td>
      <td><button type="button">Set name</button></td>
    </tr>
    <tr>
      <td>1</td>
      <td><p>Jane Doe</p></td>
      <td><input type="text" placeholder="Name"/></td>
      <td><button type="button">Set name</button></td>
    </tr>
  </tbody>
</table>

Comments