I would like to run a js function on pressing Enter button. Everything works great in IE, Chrome and Opera, but I get an error (explained below) in Safari.
I need a
A div
element has no click event handler defined per default. So, first you need to apply a click event for the enterSearch div, e.g.
. Otherwise the button itself won't be clickable.
To execute an event programmatically, use this construct:
function pressSearch(e) {
if (typeof e == 'undefined' && window.event) {
e = window.event;
}
var charCode = (e.which) ? e.which : ((e.charCode) ? e.charCode : ((e.keyCode) ? e.keyCode : 0));
if (charCode == 13) {
var a = document.getElementById('enterSearch');
if (typeof a.onclick == "function") {
a.onclick.apply(a); // binds the scope of onclick to a
}
}
}
I could not validate this for IE, but it works with Safari.