Search code examples
javascriptjquerytextareaonkeydown

Line break on keydown


I have a textarea, and on each enter i want it to get blank if something has written. but my problem is; on the first enter it line breaks, and you continue to write from the second line. it only happens at the first enter. there is no problem with emptying the textarea, you just continue to write from the second line, which is the problem.

onkeydown= if(event.keyCode == 13){

    sendMessage();
}

function sendMessage(user){

    var message = $('#textarea').val();
    $('#textarea').val('');
}

Solution

  • if(event.keyCode == 13) {
        sendMessage();
        if (event.preventDefault) event.preventDefault();
        return false;
    }
    

    keydown happens before the character is entered in the textarea, so you just have to call preventDefault on the event so it doesn't enter a line break after you've called your function that clears the text-area. return false alone should be enough too if the code above is inline in the HTML, which isn't really recommended. See updated solution below:


    For unobtrusiveness and back-compat, I'd recommend doing it all with jQuery:

    $('#textarea_ID').keydown(function(e) {
        if (e.which == 13) {
            e.preventDefault();
            var message = $(this).val();
            $(this).val('');
            //rest of your function using `message` here
        }
    });
    

    Fiddle