Bob
Bob

Reputation: 8504

jQuery not detecting enter key pressed in textarea

My setup: jQuery 1.6.2

I have this HTML

<textarea class="comment_box"> Write a comment...</textarea>  

And the following Javascript

<script>
$('.comment_box').keydown(function (e){
    if(e.keyCode == 13){
        alert('you pressed enter ^_^');
    }
})
</script>

When I press the enter key in the textarea, nothing triggers

EDIT Oops, cut and paste error, I do have $ in my code and it still doesn't work, must be something else going on.

My bad, it is a user operator error, it does work. Sorry for the confusion.

Upvotes: 4

Views: 10077

Answers (3)

Ahmad Alfy
Ahmad Alfy

Reputation: 13371

$('.comment_box').keypress(function(event) {
    // Check the keyCode and if the user pressed Enter (code = 13) 
    if (event.keyCode == 13) {
        alert('you pressed enter ^_^');
    }
});

Thats it

Upvotes: 6

mnsr
mnsr

Reputation: 12437

Check out this answer:

jQuery Event Keypress: Which key was pressed?

var code = (e.keyCode ? e.keyCode : e.which);
 if(code == 13) { //Enter keycode
   //Do something
 }

Upvotes: 2

griegs
griegs

Reputation: 22760

For jQuery you need to use the $ to specify.

$('.comment_box').keyd

should do it.

Upvotes: 0

Related Questions