Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html <td> values using javascript?

Im very new to html and javascript.

I want to get the content of element whenever the user click on a table row using javascript.

test.html

<html>
<head>
<script text="text/javascript">
function dispTblContents() {
 var pName = document.getElementById("pName").value;
 var pAddress = document.getElementById("pAddress").value;
 var pEmail = document.getElementById("pEmail").value;

 alert(pName + " " + pAddress + " " + pEmail);
}
</script>
</head>

<body>
 <table>
  <thead>
        <tr>
            <th>Name</th>
            <th>Address </th>
            <th>Email</th>
        </tr>
    </thead>

    <tbody>
        <tr onclick="dispTblContents();" >
            <td id="pName">Ricardo Lucero</td>
            <td id="pAddress">Mexico City, Mexico</td>
            <td id="pEmail">[email protected]</td>
        </tr>
    </tbody>

 </table>
</body>
</html>

Whenever I click the row it displays undefined undefined undefined. I know my code is wrong but I really don't how to fix this. Can somebody please help me. Im very new to this thing. Thanks in advance.

like image 299
NinjaBoy Avatar asked Oct 20 '11 02:10

NinjaBoy


2 Answers

You need innerHTML not value here, value is used for form elements.

<script text="text/javascript">
function dispTblContents() {
 var pName = document.getElementById("pName").innerHTML;
 var pAddress = document.getElementById("pAddress").innerHTML;
 var pEmail = document.getElementById("pEmail").innerHTML;

 alert(pName + " " + pAddress + " " + pEmail);
}
</script>

You might also want to look into jQuery if you're not using it yet, it makes selecting and manipulating HTML with Javascript a lot easier.

like image 160
Michael Low Avatar answered Sep 29 '22 02:09

Michael Low


Try change value to innerHTML

like image 40
Mr.J4mes Avatar answered Sep 29 '22 00:09

Mr.J4mes