简体   繁体   中英

I'm trying to update my div element with the value of my nameInput, isn't my code right?

I have a div element with id="firstDiv" and an input field with id="nameInput". I am trying to get the user input (from id="nameInput") and display it in my div element. shouldn't this work?

document.getElementById("firstDiv").innerHTML = document.getElementById("nameInput").value;

The short answer is yes, that code should work. I can't be sure without seeing more context but I suspect the issue you're having is that the code runs when the page loads (before you type anything into the input element).

To test that hypothesis, add a value='test' attribute to your input element and I'll bet you'll see test appear in your div.

You'll probably want to add an event handler to your input element so that your code runs whenever the input element's value changes.

html:

<div id="firstDiv"></div>
<input type="text" id="nameInput" oninput="updateDivFromInput()"></input>

javascript:

function updateDivFromInput() {
  document.getElementById("firstDiv").innerHTML = document.getElementById("nameInput").value;
}

I not so sure if I understand you,

Are you trying to throw the value of "nameInput" to your div, because if you'r, first try to :

document.getElementById("firstDiv").innerHTML = document.getElementById("nameInput").value;

Some advice, right now, we have jquery to do this simple things and a lot others,

In Jquery, you can try:

$('#firstDiv').val('#nameInput');

Yes, your code will work, as demonstrated below.

 document.getElementById("nameInput").addEventListener("keyup", function() { document.getElementById("firstDiv").innerHTML = document.getElementById("nameInput").value; }); 
 <div class="form-group"> <input type="text" id="nameInput" /> </div> <div> <h3>Output: <span id="firstDiv"></span> </h3> </div> 

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