Get column values from a table and save the value of each column in an input

Asked

Viewed 1,983 times

1

I have a table with 2 columns and I would like to, when clicking on some row, assign the values of each column of this row clicked on a <input type="text" />. I have a code that he assigns but if I click on the first column he assigns the value of the first column or the second. How do I separate it?

$('#tableTime tr td').click(function() {
    var content = $(this).text();
    $("#descricaoAgenda").val(content);
});
  • Fernando, so there is no confusion in the understanding of your question, I suggest you post also your HTML and try to describe in more detail what you are trying to do. :)

  • It had put the wrong answer, but if you have mounted your html at runtime here you can get a sense of how to do it. http://answall.com/questions/65204/criar-um-link-que-ao-ser-clicado-pego-o-seu-texto/65209#65209

  • put the html

1 answer

3


In your case use the Parent to select the tr father of tdthat was clicked, after accessing the tr use the function find to select the td's daughters and use selector :Nth-Child() to select each column of the selected row.

$('#tableTime tr td').click(function() {
    var content = $(this).parent().find(':nth-child(1)').text();
    $("#descricaoAgenda").val(content);
});

Tip: You can use the click event directly in the table row $('table tr').on('click', callback), this way, you will not need to use the parent().

See the example changed by tip, without using the parent

$('table tr').on('click', function() {
  var content1 = $(this).find(':nth-child(1)').text();
  var content2 = $(this).find(':nth-child(2)').text();
  $("#txtResultado1").val(content1);
  $("#txtResultado2").val(content2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr>
    <td>Jill</td>
    <td>Smith</td>
  </tr>
  <tr>
    <td>Eve</td>
    <td>Jackson</td>
  </tr>
</table>

<input type="text" id="txtResultado1" />
<input type="text" id="txtResultado2" />

  • i need to take the <td> element and not the <tr> element. for example: by clicking on the line (anywhere in it) send the text of the second column to an input.

  • In your question you said you need to "assign the values of each column of this row". As I answered, this is what will happen. What you really want is to take only the value of the last column of the row selects, this?

  • yes.. only that separately.. I tested the shape you gave me, only it was the value of the whole line and not each value in a different input

  • Now I understand what you really need. Already put the edited solution.

  • 1

    very good!! was that right.. I got close just missed putting the . Parent haha.. but thanks

  • 1

    +1 great answer.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.