How to handle Jquery Enter keypress event without firing multiple times and eliminate duplicate


Basky Code

The keypress event when handles without proper event handler then causes duplicate execution here is how you can fix that

// this will allow duplicates if I press enter really fast twice.
$("#messageBox").keypress(function(e) {
//alert(e.keyCode);
if(e.keyCode == 13) {
chatApp.sendMessage();
}
});

As a workaround so I can use JQuery selectors, I just get the raw DOM element instead and then attach the event to the raw DOM element by using the JS array notation:

// use Jquery to get the element, then attach event to the RAW DOM element
$('#messageBox')[0].onkeypress = function(e) {
var key = e.which||e.keyCode;
if(key == 13)
{
chatApp.sendMessage();
}
};

View original post