Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  168] [ 5]  / answers: 1 / hits: 22464  / 12 Years ago, fri, october 5, 2012, 12:00:00

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 pure Javascript solution, not jQuery.



This is the function:



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) {
document.getElementById('enterSearch').click();
}
}


This is the HTML:



<input type=text id=searchKey onkeypress=pressSearch(event)>
<div id=enterSearch>Search</div> // This is the button


I get this error:



// Safari
TypeError: 'undefined' is not a function
(evaluating 'getElementById('enterSearch').click()')


What am I doing wrong?



EDIT: I've fixed the Mozilla Firefox error.


More From » javascript

 Answers
6

If you take a look at the HTML DOM Level 2 Specification, the click() function is only defined for HTMLInputElement, so while certainly not very user-friendly Safari doesn't need to implement that.



The correct way to trigger an event for modern browsers is in DOM Level 3 Events:



// First create an event
var click_ev = document.createEvent(MouseEvents);
// initialize the event
click_ev.initEvent(click, true /* bubble */, true /* cancelable */);
// trigger the event
document.getElementById(someElement).dispatchEvent(click_ev);


Here's jsfiddle that works in Chrome, Safari, Firefox and IE9: http://jsfiddle.net/y5yW9/6/


[#82738] Wednesday, October 3, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emiliano

Total Points: 381
Total Questions: 109
Total Answers: 93

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
emiliano questions
;