如何根据输入到表单中的内容改变Div的值

how to change the value of a Div according to whats typed into a form input

本文关键字:改变 Div 的值 何根 输入 表单      更新时间:2023-09-26

我知道如果我想根据用户在另一个输入中输入的内容更改表单上的输入值:

$('#inputName').change(function() {
    $('#inputURL').val($('#inputName').val());
});

但我想有它,所以当有人输入它更新一个Div与文本代替输入。IE中输入#inputName,结果如下:

<div id="personsName"> text appears here as they type</div>

我该怎么做呢?当我将#inputURL更改为#personsName:(

)时,我不工作

change事件仅在离开文本字段时触发,因此如果您真的想要"在输入文本字段时更新文本",则使用keypress代替。.val仅适用于实际具有值的表单元素(例如<input><textarea>元素)。在所有其他情况下,您需要text方法来修改文本。

$("#inputName").keypress(function () {
    $("#personName").text(this.value);
});

您可以在这里测试此代码:http://jsfiddle.net/ntBnA/

你就快成功了:

$('#inputName').change(function() {
    $('#personsName').text($('#inputName').val());
});
//Cache this bad boy, its being repeatedly used!
var personsName = $('#personsName');
$('#inputName').bind({
  keyup: function () {
    //This is what you want.
    personsName.text($(this).val());
  },
  change: function () {
    //This is what you were doing.  See the difference?
    $('#inputURL').val($(this).val());
  }
});