Vítor Resende
Vítor Resende

Reputation: 260

jQuery get enter event but don't enter after

I've been using jQuery to get enter event. As you can see below, when we press enter in the text area, we got the alert but after, the text is entered. I've tried everything but I couldn't find what I could do. Could someone help me?

var jchat = jQuery.noConflict();
jchat("#msg-txt").keypress(function(e){
        var keycode = (e.keyCode ? e.keyCode : e.which);
        if (keycode == '13'){
            e.stopPropagation();
            if(event.shiftKey){
                if (jchat('#msg-txt').attr('rows') == '1')
                    jchat('#msg-txt').attr('rows', '2');
            } else {
                messageText = jchat('#msg-txt').val();
                alert(messageText)
            }
        }
        
    })
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>

<textarea id="msg-txt" rows="4" cols="50">
lalalalalaalalala teste lalala
</textarea>

</body>
</html>

Upvotes: 0

Views: 58

Answers (4)

dganenco
dganenco

Reputation: 1616

But my guess is, that you should use keydown event instead. Also your next statement is unreachable

if(event.shiftKey){
                if (jchat('#msg-txt').attr('rows') == '1')
                    jchat('#msg-txt').attr('rows', '2');
            }

Btw, here an example with keydown event:

var jchat = jQuery.noConflict();
jchat("#msg-txt").on('keydown', function(e){
        var keycode = (e.keyCode ? e.keyCode : e.which);
        if (keycode == '13'){
            e. preventDefault();
            if(event.shiftKey){
                if (jchat('#msg-txt').attr('rows') == '1')
                    jchat('#msg-txt').attr('rows', '2');
            } else {
                messageText = jchat('#msg-txt').val();
                alert(messageText)
            }
        }

    })

Upvotes: 0

KENZiE
KENZiE

Reputation: 304

Use e.preventDefault(); instead of e.stopPropagation();

Upvotes: 3

ebilgin
ebilgin

Reputation: 1252

You need to change

e.stopPropagation();

with

e.preventDefault();

Detailed information will be here.

https://developer.mozilla.org/tr/docs/Web/API/Event/preventDefault

Upvotes: 2

brk
brk

Reputation: 50316

Try by replacing jchat("#msg-txt").keypress(function(e){ with jchat("#msg-txt").keyup(function(e){

Upvotes: 0

Related Questions