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.
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.
Try change value to innerHTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With