How to instantly output text from input to divs. We have a regular input and divs. When we write any text in the input, it automatically appears in the diva.
2 answers
To solve the problem, you can use the oninput event:
function onInput() { var input = document.getElementById("input"); var div = document.getElementById("div"); if (div != null && input != null) div.innerHTML = input.value; } <input type="text" id="input" oninput="onInput();"/> <div id="div" /> The question arises: why not onkeyup ? For two reasons.
First, when the button is held down, the input to the input will continue, and changes will get to the div only when the button is released.
And secondly, input is possible without the help of a keyboard, for example, inserting a mouse click on the context menu. In this case, the onkeyup handler will not be called at all.
PS There may be problems with IE9 and older ( https://learn.javascript.ru/events-change#%D1%81%D0%BE%D0%B1%D1%8EBD% B5-input ).
- And how to display a function in a separate file js, when I insert it into a file, it stops working - nicolaa
- @ user232379 Transfer the function to a file and connect it:
<script src="..."></script>. - user194374
|
In a hurry - add a click handler in your input, which will copy the contents of the input in the div.
var input = document.getElementById("input"); var div = document.getElementById("div"); input.addEventListener("keyup", function() { div.innerText = input.value; }) #div { height: 200px; border: 2px solid; } <input id="input" type="text"> <div id="div"></div> |