3

I noticed the new Facebook way of sending comments on status. Basically when you write your comment you have no buttons to click but the "enter" key to press in order to submit the comment. Now I'd like to make this thing too. And I was thinking about the possible solutions. It comes to my mind that <input> are submitted with the enter button pressed, but that textarea are not.

  • Either I write an input (type text) and set an height witch covers more than a row
  • Or I have to add a textarea and somehow submit that form when the user press enter.

Which is the best? And if the answer = second, how could I do that?

Shoe
  • 74,840
  • 36
  • 166
  • 272

4 Answers4

9

It depends how you define best.

The first is best if you want a really easy solution that doesn't require javascript

The seconds is best if you wish to allow linebreaks in the text.

If you wish to use the text area solution you can do something like this: (uses jQuery)

<textarea id="mytextarea"></textarea>
<script>
$('#mytextarea').keypress(function(e){
  if(e.keyCode == 13 && !e.shiftKey) {
   e.preventDefault();
   this.form.submit();
  }
});
</script>

The good thing about this solution is that it still allows people to do linebreaks, if they just hold in the shift key when they hit enter. Just like on skype.

Live example here: http://jsfiddle.net/MEtGg/

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
1

No need for a framework (such as jQuery) just for this:

var textarea = document.getElementById("area");

try {
    textarea.addEventListener("keydown", keyPress, false);
} catch (e) {
    textarea.attachEvent("onkeydown", keyPress);
}

function keyPress(e) {
    if (e.keyCode === 13) {
        alert("Enter key was pressed")
    } else {
        return;
    }
}

Take a look at an example here: http://fiddle.jshell.net/yuCAd/3/

Shaz
  • 15,637
  • 3
  • 41
  • 59
0

I'd register a key listener on the enter key when the focus is in your textarea, that's the most common and best way imo.

in jquery you can use the keydown/up method

ChrisR
  • 14,370
  • 16
  • 70
  • 107
0

I would go with the second. And will use javascript to intercept the enter key and then call a function to do the submit. This answer should do the case: Trigger a button click with JavaScript on the Enter key in a text box

Community
  • 1
  • 1
Iridio
  • 9,213
  • 4
  • 49
  • 71