Reputation: 47605
How do you catch a carriage-return in a textarea and do a form post instead of a newline in the textarea?
Upvotes: 8
Views: 8414
Reputation: 359816
The basic skeleton (from the API docs):
$('#textarea-selector-here').keydown(function(event)
{
switch(event.keyCode)
{
// ...
// different keys do different things
// Different browsers provide different codes
// see here for details: http://unixpapa.com/js/key.html
// ...
}
});
However, if you don't want to allow multiline input, why not just use an <input type="text" />
?
Upvotes: 1
Reputation: 827326
Capture the keystroke, verify if it is enter, and then look for the parent form
element and submit it:
$('#textAreaId').keydown(function (e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 13) {
$(this).parents('form').submit();
return false;
}
});
Check the above example here.
Upvotes: 15
Reputation: 51935
Add an onKeyPress function to the textarea, and have it intercept Enter (character code 13) and submit the form instead.
Here's an example that uses a text input instead of textarea, but it should work the same way.
<textarea name="myTextArea" onKeyPress="checkEnter(event)"></textarea>
Upvotes: 1