Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  121] [ 6]  / answers: 1 / hits: 15267  / 13 Years ago, fri, november 18, 2011, 12:00:00

I have the following simple <textarea>


<textarea id="streamWriter" rows="1" cols="20" placeholder="Writer"></textarea>

Also I have the following jQuery/JavaScript code block:


$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
alert('ctrl enter - go down a line as normal return would');
return true;
}
e.preventDefault();
alert('submit - not your default behavior');
}
});

I'm trying to force the not to create a new line break on normal return keydown. But I want this behavior if Ctrl+Enter was typed instead.


This does detect the difference but is not forcing the behavior that I need.
If you've used Windows Live Messenger, I need the same textbox behavior. Enter to submit (In my case I will call a function but stop the textarea from going down a line) and Ctrl+Enter go down a line.


Solutions? Thanks.


Update:


$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode == 13) {
if (e.ctrlKey) {
//emulate enter press with a line break here.
return true;
}
e.preventDefault();
$('div#writerGadgets input[type=button]').click();
}
});

The above does what I am trying to do. There is just the part to emulate enter press with a line break. Please let me know how to do this if you know.


More From » jquery

 Answers
63

Using keypress instead of keydown works a little better, however will not work with the Ctrl key; I switched to the shift key - jsfiddle.



Edit: As far as I can tell, you won't be able to use Ctrl key consistently cross browser because the browser uses it for it's own short-cuts. You would run into the same situation with the alt key.



Edit again: I have a solution that works with the Ctrl key - jsfiddle.



$('textarea#streamWriter').keydown(function (e) {
if (e.keyCode === 13 && e.ctrlKey) {
//console.log(enterKeyDown+ctrl);
$(this).val(function(i,val){
return val + n;
});
}
}).keypress(function(e){
if (e.keyCode === 13 && !e.ctrlKey) {
alert('submit');
return false;
}
});


Edit: This doesn't work 100%, it only works if you are not in the middle of text. Gonna have to work on a way to have the code work on text in the middle.



By the way... Why are you doing it this way? Wouldn't it be confusing to the user if they pressed enter to make a new line and the form all of a sudden submitted before they were ready?


[#89031] Thursday, November 17, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
moriah

Total Points: 201
Total Questions: 100
Total Answers: 82

Location: Tuvalu
Member since Sun, Sep 4, 2022
2 Years ago
moriah questions
Mon, Aug 17, 20, 00:00, 4 Years ago
Tue, Nov 12, 19, 00:00, 5 Years ago
Wed, Aug 7, 19, 00:00, 5 Years ago
Tue, Jul 9, 19, 00:00, 5 Years ago
;