Curtis Chong
Curtis Chong

Reputation: 811

How do I detect the "enter" key and "shift" key at the same time to insert a line break

I'm trying to create a note system. Whatever you type into the form gets put into a div. When the user hits Enter, they submit the note. However I want to make it so when they hit Shift + Enter it creates a line break a the point where they're typing (like skype). Here's my code:

$('#inputpnote').keypress(function(event){

    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode=='13' && event.shiftKey){
        $("inputpnote").append("<br>");
    }
    else if(keycode == '13'){
        var $pnote = document.getElementById("inputpnote").value;
        if ($pnote.length > 0) {
            $("#pnotes-list").append("<div class='pnote-list'><li>" + $pnote + "</li></div>");
            $('#inputpnote').val('');
        }
    }

});

#inputpnote is the form where the user enters their note and #pnotes-list is the place where the notes are being appended to. Thank you in advance!

Upvotes: 0

Views: 257

Answers (1)

user2836518
user2836518

Reputation:

I think for this you'd have to set two global variables, 1 for shitftKeyPress and 1 for enterKeyPress and then you'd need a keydown and a keyup to set those values and then you check to see if they are both true, because your logic is saying, when a key is pressed, execute this code, if you press a key and then press another key, the only that will happen is the function will be called twice.

EDIT: Example code of what it should look like:

var hasPressedShift = false;
var hasPressedEnter = false;

$('#inputpnote').keydown(function(event){
    if(shiftkey) {
        hasPressedShift = true;
    }

    if(enterKey) {
        hasPressedEnter = true;
    }
});

$('#inputpnote').keyup(function(event){
    if(shiftkey) {
        hasPressedShift = false;
    }

    if(enterKey) {
        hasPressedEnter = false;
    }
});

$('#inputpnote').keypress(function(event){
    if(hasPressedShift && hasPressedEnter) {
        // Do something
    }
});

This was a quick mock up, but it's similar to how it should look

Upvotes: 2

Related Questions