krimz krimz - 7 months ago 15
Javascript Question

Change span when text field changes as you type

I want text in the

span
field to change as the
input
field changes
live
.

So I have a
input
field

<input type="text">


and a
span
field

<span></span>


I want text in the
span
field to change as I type in the
input
field.

I know there's already a question like this that was asked Change span when text field changes. But what makes this question different is the changes should happen as you type i.e.
live
.

Answer

Here is a vanilla JavaScript version.

var input  = document.querySelector("[type=text]"),
    output = document.querySelector(".output");

function keydownHandler() {
  output.innerHTML = this.value;
}

input.addEventListener("input", keydownHandler);
<input type="text">
<span class="output"></span>