How to take the value of a selected line from an html table

Asked

Viewed 954 times

1

I would like to click on a row of the table to return the value of the selected column only. My code brings all values of the tags td however as the table will be dynamically mounted need it to display only the value of the selected line. function selLinha(linha, multiplos) { var dados = ""; dados += "ID: " + document.getElementsByTagName("td")[3].innerHTML; alert(dados); } Note that to get the value you need to pass its position on the tag etElementsByTagName("td")[3]. html table <thead> <tr> <th>IP</th> <th>ID</th> </tr> <tbody> <tr style=" cursor: pointer;" onclick="ts()"> <td style=" cursor: pointer;">12</td> </tr> <tr style=" cursor: pointer;" onclick="ts()"> <td style=" cursor: pointer;">22</td> </tr> </tbody> </thead>

1 answer

2


If I understand you need to make one forEach to catch each td clicked, then you use a e.currentTarget.id to catch only the id of the clicked element

inserir a descrição da imagem aqui

Follow the image code above

var td = document.querySelectorAll('td');

td.forEach((el) => {
    el.addEventListener('click', meuID);
});

function meuID(e) {
    console.log(e.currentTarget.id);
}
<table>

    <thead>
        <tr>
            <th>IP</th>
            <th>ID</th>
        </tr>
    </thead>
    <tbody>
        <tr style="  cursor: pointer;">
            <td style="  cursor: pointer;" id="n1">12</td>
        </tr>
        <tr style="  cursor: pointer;">
            <td style="  cursor: pointer;" id="n2">22</td>
        </tr>
    </tbody>

</table>

  • Forgive the ignorance , but why didn’t you use the "onclick"?

  • @Matheusisac I won’t say that onclick if a bad practice, but is unnecessary in most cases. Until pq if you have 100 elements and want to change for example from onclick to mouseover, or change the function name, you have to change the code in the 100 elements. In addition to repeating code atoa since the way I did it would save you some Kbs depending on the size of the table. To finish it is not very good to maintain the system, because it is difficult to know which selector is calling the function, you will have to look in the code who has the onclick, with the selector set you already see it direct

Browser other questions tagged

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