Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 735
krimz Avatar asked Apr 25 '16 09:04

krimz


3 Answers

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>
like image 120
Andy Hoffman Avatar answered Nov 13 '22 21:11

Andy Hoffman


Very simple, use a keyup event.

$(function () {
  $("input").keyup(function () {
    $("span").text(this.value);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<p><span></span></p>

In the latest browsers, you can use oninput event.

like image 20
Praveen Kumar Purushothaman Avatar answered Nov 13 '22 22:11

Praveen Kumar Purushothaman


You can use HTML5 input event, listen the event using on()

$('.input').on('input', function() {
  $('.span').text(this.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="input">
<br><span class="span"></span>

JavaScript solution with input event

function change(val) {
  document.querySelector('.span').innerHTML = val;
}
<input type="text" oninput="change(this.value)">
<br><span class="span"></span>
like image 3
Pranav C Balan Avatar answered Nov 13 '22 22:11

Pranav C Balan