简体   繁体   中英

How to simulate typing into a textarea using Javascript/Jquery?

I have a textarea which uses a jquery plugin to resize itself while the user types in it.

The problem is, I want users to be able to edit things they've already typed. However since the textarea starts with 35 cols, 1 row, if the user had a long message he typed, then it doesn't completely show, only one line shows which cuts off.

Is there a way to simulate a keypress event in that textarea, so that the text resizing will fire up and resize the textarea?

There's no way to programatically call the text resize function.

Just trigger the keypress event on that textarea:

$(function(){
     $('textarea').trigger('keypress');
}).

if there are multiple textareas, and you want to trigger the event on a specific textarea that has an id, of course the syntax becomes:

$(function(){
     $('#myTextarea').trigger('keypress');
}).

If this is your own code, then you can just call your function

Your text area likely already has some function that gets called on each keystroke. The simplest way for you is then to call this same function when your page loads and that's it.

<textarea onkeypress="someFunc();" />

just call this someFunc when page loads and it should do the same thing as if you pressed a key.

Not written by you? Using third party plugins then

If you're using some sort of a jQuery plugin (not your own) then you should check whether it provides this functionality to initially set text area's size. If it doesn't then I suggest you switch to a different plugin that does that. Or write your own if you know how.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM