views:

169

answers:

3

I have a textarea that when a users pressed enter/return on their keyboard, I want to submit the field to a JavaScript function, just like it works on Twitter.

Ideas?

Thanks

+1  A: 

Subscribe for the onkeydown event and detect the return key code.

Jakub Hampl
+2  A: 

Just use a normal text input, this functionality comes built-in. Textareas are supposed to be "returnable", making the form submit on return in a textarea will confuse your users.

Galen
+2  A: 

If you're using jQuery, you could do this:

$('#myTextarea').keydown(function(e) {
    if(e.which == 13) {
        // Enter was pressed. Run your code.
    }
});

The keypress handler runs on each key press, and tests for the 'enter' key.

EDIT:

Changed keypress to keydown, as keypress may run the code multiple times if the user holds down Enter. Probably not what is desired.

patrick dw
Why `which` and not `keyCode`?
eyelidlessness
@eyelidlessness - keyCode would be fine too. I've just used `e.which` upon jQuery docs recommendation http://api.jquery.com/event.which/, but in this case, there isn't any specific benefit.
patrick dw
@patrick Your answer is not complete ;) : `charCode` takes all characters ('a', 'Q' etc.) in count. If not a character was pressed, then the value the code will be stored in `keyCode` ('Enter', 'Tab' etc). `which` covers both `keyCode` and `charCode`.
Harmen
@Harmen - Yeah, I was lazy and just linked to the docs. Your explanation is much more thorough. Thanks for your input. :) In this particular case (just testing for `Enter`), there isn't much compelling reason to use one over the other.
patrick dw