Little Lux Little Lux - 25 days ago 5x
HTML Question

document.getElementById for an element in external html

I have this html:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">

<script type="text/javascript" src="notas.js"></script>


<p>Nombre alumno: </p>
<input type="text" name="nombre" id="nombre">
<p>Nota alumno:</p>
<input type="text" name="nota">

<input type="button" name="boton" value="Enviar" onclick="respuesta()">


And this Javascript in another file:

function respuesta(){


The problem is that when I click the button the message is "null"
I have see solutions to a similar problem in the forum but I don't know what to do since there's a button. Help!


There are a couple of problems there:

  1. You haven't declared nombrej. (And shouldn't that be nombre?) That means your code is falling prey to The Horror of Implict Globals (that's a post on my blog). Declare your variables.

  2. You've set nombrej to the HTMLInputElement. You probably wanted its value, which is on its value property.

  3. Calling document.write once the page has been completed will implicitly call, which wipes out the page and replaces it with what you write.

So respuesta might look something like this instead:

function respuesta(){

    var nombrej=document.getElementById("nombre").value;
//  ^^^--- #1                                    ^^^^^^--- #2
//  ^^^^^^^^^^^--- #3

Side note: I see you've put your script tag in the head section. You'll find a lot of people doing that and telling you to do it, but it's an anti-pattern. Unless you have a specific reason to do something else, put script tags at the very end of body, just before the closing </body> tag. More in YUI's guidelines.