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

Anas

New Member
#1
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?
Mã:
document.getElementById("firstDiv").innerHTML = document.getElementById("nameInput").value;
 

Admin

Administrator
Thành viên BQT
#2
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:
Mã:
<div id="firstDiv"></div>
<input type="text" id="nameInput" oninput="updateDivFromInput()"></input>
javascript:
Mã:
function updateDivFromInput() {
  document.getElementById("firstDiv").innerHTML = document.getElementById("nameInput").value;
}
 
Top