Bryan
Bryan

Reputation: 358

Multiple key press function in jquery?

I have a textarea field that submit the information when the user press the enter key. Below is what I have:

$(document)ready(function(){
    $('textarea').on('keypress',function(e){
        var txt;
        txt = $(this).val();

        if(e.which == 13)
        {
            //submit the form
        }

    });
});

What I would like to do is submit information when the user presses only the enter key, and do a hard return when the user presses and holds the control key and press enter. (The above code is working fine) I just do not know how to add the other code for the press and hold option. Please explain answer.

Upvotes: 0

Views: 237

Answers (2)

Dennis Bartlett
Dennis Bartlett

Reputation: 61

Below is a solution that does exactly what you asked for. The code in the JSfiddle has some CSS to show you it works. When you press Enter it will change the color of the text area (you would replace that with your code for submit) but when you press Shift+Enter, it will create a new line and continue editing.

Cheers :D

http://jsfiddle.net/5Kc2T/1/

$(document).ready(function () {
    $('textarea').on('keypress', function (e) {
        var txt = $(this);

        if (e.which == 13) {
            e.preventDefault();
            if (e.shiftKey === true) {
                txt.val(txt.val() + "\n");
            } else {
                //Submit Code Here
            }
        }
    });
});

Upvotes: 1

jfriend00
jfriend00

Reputation: 707308

You can use e.ctrlKey:

$(document).ready(function(){
    $('textarea').on('keypress',function(e) {
        var txt=$(this).val();

        if(e.which === 13 || e.which === 10) {
            if (e.ctrlKey) {
                // handle ctrl-ret here
            } else {
                //submit the form
            }
        }
  });
});

Related question here: detecting ctrl+tab key press in javascript/jQuery

Upvotes: 2

Related Questions