4

I've got the following code:

document.onkeydown=function(e) {
if (e.which == 13 && isCtrl) {
   log('Ctrl CR');
} else if (e.which == 17) {
   isCtrl = true;
};

I need to insert a Carriage Return/Line feed where the cursor is located in the input textarea. Now that I think about it, I should probably be using a textarea selector instead of document.onkeydown, but $('textarea').onkeydown doesn't work.

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

1 Answers1

8
$('textarea').keydown(function (e){
    var $this = $(this);
    if (e.which === 13 && e.ctrlKey) {
        $this.val($this.val() + '\r\n'); // untested code (to add CRLF)
    }
});

Reference

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Your solution might add it to the end, but what if the cursor is positioned in the middle? – Phillip Senn Apr 15 '11 at 20:47
  • Yes, that's definitely a problem. However, there's [information enough on SO already to answer that part](http://stackoverflow.com/questions/946534). – Matt Ball Apr 15 '11 at 20:52