how to change the value of a Div according to whats typed into a form input
I know if I want to change the value of an input on a form according to what a user types into another input using:
$('#inputNa开发者_开发知识库me').change(function() {
$('#inputURL').val($('#inputName').val());
});
But I'd like to have it so when someone types into the input it updates a Div with the text instead. IE they type into #inputName and this happens:
<div id="personsName"> text appears here as they type</div>
How'd I go about doing that? I doesn't work when I change #inputURL into #personsName :(
The change
event is only triggered when leaving the textfield, so use keypress
instead if you really want to "update the text on typing into a text field". .val
only applies to form elements which actually have a value (e.g. <input>
and <textarea>
elements). In all other cases, you need the text
method for modifying the text .
$("#inputName").keypress(function () {
$("#personName").text(this.value);
});
You can test this code here: http://jsfiddle.net/ntBnA/
You're almost there:
$('#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());
}
});
精彩评论