简体   繁体   中英

document.getElementById for an element in external html

I have this html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Notas</title>

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

</head>
<body>

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

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

</body>
</html>

And this Javascript in another file:

function respuesta(){

    nombrej=document.getElementById("nombre");
    document.write(nombrej);
} 

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 document.open , 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
    console.log(nombrej);
//  ^^^^^^^^^^^--- #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 .

JavaScript getElementById returns the DOM element. To get the value of that text input, you need to get the value of it.

Instead of: nombrej=document.getElementById("nombre");

Use: nombrej=document.getElementById("nombre").value;

Examples: JavaScript: how to get value of text input field?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM