简体   繁体   中英

How can i add or change text to a <div> element from javascript

I am trying to create a program that takes whatever text you input and (for now) shows it in a element.

Here is what i have of code:
HTML:

 <body>
     <center><h1><b>J.A.I.</b></h1>
     <!--dialogue-->
     <div id= "dialogue"></div>
     <!--input-->
     <input id="text" type='text'></input>
 </center>
 </body>

Javascript:

 //takes input from <input type=text>
 function takeInput() {
     var question = this.value;
     displayOutput(question, output);
 }

 //displays output
 //@param message string Message to be displayed
 //@param destination HTML element where the message is to be displayed
 function displayOutput(message, destination) {
     destination.innerHTML = message;
 }

 //init code

 var input = document.getElementById("text");

 var output = document.getElementById("dialogue");

 input.onkeydown = takeInput();

I am using firefox 31.4.0 and the error i get says:

TypeError: destination is null

what am i doing wrong?

You need to assign the function to the event:

input.onkeydown = takeInput;

You were immediately calling the function instead.

I think it is because you are using "text" as an id name, and it is reserved. Don't use it as an ID. Also, i have chosen to bind the function in the HTML. So change it to:

<input id="txtField" type='text' onkeyup="takeInput()"></input>

And change the JS to get that ID as well:

var input = document.getElementById("txtField");

Here is a working JSFiddle: https://jsfiddle.net/6t4pkn3j/11/

Note, in my JSFiddle i moved some code around. I find it more clean to gather everything in functions and not leave those global variables hanging around :)

Hope it helps. /JBJ

* EDIT * Seems 'text' is not a reserved word after all :-) The issue probably laid with event binding then (second part of my answer). Here is a new JSFiddle that uses 'text' as an id: https://jsfiddle.net/6t4pkn3j/12/

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