2011-10-20 28 views
6

Soy muy nuevo en html y javascript.¿Cómo obtener html <td> valores usando javascript?

Quiero obtener el contenido del elemento siempre que el usuario haga clic en una fila de la tabla mediante 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> 

Cada vez que hago clic en la fila que muestra undefined undefined undefined. Sé que mi código es incorrecto, pero realmente no sé cómo solucionarlo. ¿Puede alguien por favor ayudarme? Soy muy nuevo en esto. Gracias por adelantado.

Respuesta

11

Necesita innerHTML no aquí, value se utiliza para elementos de formulario.

<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> 

También puede ser que desee ver en jQuery si no lo está utilizando, sin embargo, se hace la selección y manipulación de HTML con Javascript mucho más fácil.

+0

Usar * innerText * o * textContent * (según corresponda) sería mejor para que no se devuelva el marcado. – RobG

1

cambio Try value a innerHTML

1

intenta cambiar valor a innerHTML o innerText

document.forms[0].getElementsByTagId("pName").innerText; 
1

Una etiqueta <td> no tiene un valor .

Use document.getElementById("pName").innerHTML en su lugar.

1

También busqué mucho. Finalmente puedo ver la solución de los maestros. Este es un ejemplo que funciona:

........... 
    <head>    
     <script type="text/javascript"> 

     function ChangeColor(tableRow, highLight) 
     { 
      if (highLight){ 
       tableRow.style.backgroundColor = '00CCCC'; 
      } 

     else{ 
      tableRow.style.backgroundColor = 'white'; 
      } 
     } 

     function DoNav(theUrl) 
     { 
     document.location.href = theUrl; 
     } 
     </script> 

    </head> 

    <% ArrayList<Student> students = StudentsManager.getInstance().getStudents(); %> 

    <body> 
     Choose a student <br> 

     <table> 
      <tr> 
      <td> 
      <table id = "c" width="180" border="1" cellpadding="0" cellspacing="0"> 

      <% for (Student st : students){ %> 

      <tr onmouseover="ChangeColor(this, true);" 
       onmouseout="ChangeColor(this, false);" 
       onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=<%=st.getStudentId()%>');"> 

       <td name = "title" align = "center"><%= st.getStudentId() %></td> 

      </tr> 
      <%}%> 

............... 

estudiantes es un ArrayList que contiene objetos de tipo Student (studentID, nombre). La tabla muestra a todos los estudiantes. Antes de hacer clic en una celda, haga clic en Ver fuente. Verá:

<tr onmouseover="ChangeColor(this, true);" 
      onmouseout="ChangeColor(this, false);" 
      onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=1');"> 

      <td name = "title" align = "center">1</td> 

     </tr> 

Bueno en mi caso era "1". No hice la página de destino todavía.

Cuestiones relacionadas