Search code examples
javascriptsubmitmessageenterkeycode

Enter key javascript keypress not working


I've got a bit of Javascript which the end goal is for whenever the "enter" key is pressed, a message is appended to my unordered list. Right now, any key that is pressed is appended rather than it just being the "enter" key. For example if I typed "Y", that would be submitted on the press of any other button. Obviously, all I want is data thats been typed into the text-box, submitted through "enter".

My HTML:

<ul id="messagebox" >
</ul>

<div>
    <input type="text" id="typetextbox" maxlength="120" autocomplete="off" />
    <button type="submit" id="submit" onblur="submit"> </button>
</div> 

Here is the button trigger piece of Javascript:

$(document).ready(function(){
    $('#typetextbox').keypress(function (e){
        if(e.keyCode == 13 );
        $('#submit').click();
    });
});

And here is the Javascript that works for appending the messages:

$(document).ready(function(){

    $('#submit').click(function(){
        var message = $('#typetextbox').val();
        $('#messagebox').append(message + "<br/>");
        $("#typetextbox").val("");  
    });
});

Why isn't it singling out just the Enter button to submit?


Solution

  • keyCode is actually a property of the event, so you have to use e.keyCode. Also you were calling if(keyCode == 13 );: that semicolon (;) right after the closed parenthesis, ends the if-statement immediately, so the next line of code is always executed.

    Here is the correct code:

    $('#typetextbox').keypress(function (e){
        if(e.keyCode == 13 ) $('#submit').click();
    });
    

    To append the message to the ul element you should create a li element first, then append it to the ul element.

    Here is the correct code:

    $('#submit').click(function() {
        var message = $('#typetextbox').val();
    
        if (message.replace(/ /g, '')) // If the text is not empty (e.g. nothing or only spaces)
            $('#messagebox').append( $('<li>', {text: message}) );
        $("#typetextbox").val("");  
    });
    

    By the way, you don't need the $(document).ready function to do this. Just put your script after the textarea in the dom and it will work fine.

    HERE'S THE FIDDLE: http://jsfiddle.net/t7q4j/1/