3

I have a textarea with rows="1" inside a <td>, so it takes up as little space as possible when empty.

Now I was wondering, how would I best "expand" the textarea when the user presses the enter key?

I have put up a very simple jsfiddle to test the idea. Unfortunately I am not very good with jsfiddle, so I did not know how (or if) is it possible to use .on() or other event listeners, so I have simply put up a one-time update that runs when the jsfiddle is ran.

So far it works, but I was wondering if there's a better/more efficient way to do it.

PS to call the function I was thinking to use keypress and then this code found here on SO

var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
  //expand()
}
4

1 回答 1

2

Try this:

$('.expand').on('keypress', function (e) {

    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) {
        // Enter pressed... do anything here...
        var rows = $(this).attr('rows');
        var rowsNew = parseInt(rows) + 1;
        $(this).attr('rows', rowsNew);
    }
});

DEMO HERE

于 2013-04-19T10:53:38.333 回答