I'm using the simple code below to replace a textbox (<input type=text />
) with a <textarea>
element after the user types in a certain number of characters. In the example below, this takes place after the 10th character. The code works, except that the contents of the <textarea>
omits the 10th character that the user typed. For example, if you type "testing 1234" in the textbox, the textarea will omit the "4". Any ideas? Thanks. --Jake
$('.info').keypress(function() {
var count = $(this).val().length;
if (count > 10)
{
var contents = $(this).val();
$(this).after('<textarea></textarea>').next().val(contents).end().remove()
}
})
UPDATE: I tried the suggestion many of you shared: using the keyup event. It works, but only if you type slowly. If you're a fast typer, like I suspect most people here would be, the 10th character is still omitted when using the keyup event.
Perhaps you should use textarea from the start, augmenting "rows" attribute only. I'd be willing to bet you'd maintain all your characters after the change and it would behave exactly like a textbox with rows="1".
$('.info').keypress(function() {
var count = this.value.length;
if (this.rows == 1 && count > 10)
{
this.rows = 4; // Or whatever you'd prefer.
}
});