Change span when text field changes as you type

笑着哭i 提交于 2021-02-07 14:22:17

问题


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.


回答1:


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>



回答2:


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.




回答3:


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>


来源:https://stackoverflow.com/questions/36836631/change-span-when-text-field-changes-as-you-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!