'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 1:[1]
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/
Solution 2:[2]
update html code as
<div>
<input type="text" id="typetextbox" onkeypress="return keyPress(event)" maxlength="120" autocomplete="off" />
<button type="submit" id="submit" onblur="submit"> </button>
</div>
java script implementation:
for every keypress the function keyPress(event) will be called.
the function definition can be
var keyPress = function(e){
if(e.keyCode == 13){
send();
}
return true;
}
the function send consists of code for updating the message box
Solution 3:[3]
Try below code, it's working properly.
$(document).on("keypress", function (event) {
if (event.keyCode === 13) {
alert('You hit me')
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Saiteja Parsi |
| Solution 3 | Rosidin Bima |
