Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to replace textbox with <textarea> after certain character length

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.

like image 405
jake Avatar asked Nov 11 '10 14:11

jake


People also ask

How to restrict character length in textbox using jQuery?

Limit character input in the textarea including count. JavaScript Code : var maxLength = 15; $('textarea'). keyup(function() { var textlen = maxLength - $(this).

How do you limit character input in textarea including count in jQuery?

We create an input text area with a given maxlength and then use jQuery code to limit the characters. First, we set the max limit and then use keyup() method to reduce the textarea character limit by 1 when we click the button and display the count on the screen. Syntax: var max_length = 25; $('textarea').

How to limit number of characters in textarea?

The HTML <Textarea>maxlength attribute is used to specify the maximum number of characters enters into the Textarea element. Attribute Value: number: It contains single value number which allows the maximum number of character in Textarea element.

What is the way to keep users from typing text into a large text area?

What is the way to keep users from typing text into a large text area? For input type="text" , we can use the size attribute to specify the visible size of the field, in characters. But we can also use the maxlength attribute to specify the maximum amount of characters that can be entered.


1 Answers

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.
    }
});
like image 196
Neil Avatar answered Oct 08 '22 12:10

Neil