3

I'm working on a textarea, where if the user hits enter, it causes the form to submit, but if he hits ctrl + enter, I want it to move to the next line.

This is the code that I'm using, within my function which is called on keypress by jquery:

if ( (e.keyCode == 10 || e.keyCode == 13) && e.ctrlKey)
    //move to next line here

Any ideas how to do this?

Ali
  • 261,656
  • 265
  • 575
  • 769

2 Answers2

2
$('.parentElementClass').on('keyup', 'textarea', function(e) {
    if(e.ctrlKey && (e.which == 13 || e.keyCode == 13)) {
        $(this).val(function(i, val) {
            return val + '\n';
        });
    }
});

demo

Ricardo Alvaro Lohmann
  • 26,031
  • 7
  • 82
  • 82
1

It's all set now! Breakline at any point & it maintains position (all while trying to use the most up to date browser techniques with fallbacks for IE, etc).

UPDATED x2 - jsFiddle link

$('#sillyTextarea').keydown(function (e) {

    if (e.keyCode === 10 || e.keyCode  == 13 && e.ctrlKey) {
        // Ctrl-Enter pressed
        // keyCode 10 is actually for Chrome (whacky I know...)

        var el = document.getElementById('sillyTextarea'),
            allText = $(this).val(),
            currentPos = getCaret(el),
            beforeText = allText.substr(0, currentPos),
            afterText = allText.substr(currentPos);

        $(this).val(beforeText + '\n' + afterText);

        setCaretPosition(el, currentPos);
    }
});

With help of 2 functions

function getCaret(el) { }

Caret position in textarea, in characters from the start

function setCaretPosition(el, caretPos) { }

Set keyboard caret position in html textbox

Community
  • 1
  • 1
Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96