[SalesForce] onkeypress event not working in chrome but works well in firefox

I have implemented a visualforce page containing an inputText box for searching. I have used javascript "onkeypress" event in my visual force page. onkeypress event is fired when the value of a textbox changes and it works well in Firefox. But the same event is not fired in Chrome. I have tried using onchange event but its not working in both the browsers.

You may refer the snippet as below:

<apex:inputText value="{!strSearch}" onkeypress="return SetTimer(event);" id="txtSearch">
function SetTimer(e){
            var strKeyCode = ',9,17,18,20,33,34,35,36,37,38,39,40,45,91,92,93,112,113,114,115,116,117,118,119,120,121,122,123,144,145,'
            var eventInstance = window.event ? event : e;
            var keyCode = eventInstance.charCode ? eventInstance.charCode : eventInstance.keyCode;
            if(e.keyCode == 13){                
                return false;

            }else if(strKeyCode.indexOf(','+e.keyCode+',') == -1){
                var t=setTimeout("Search()",1000);
                setSubmit();
            }             
            else{
                var txtSearch = document.getElementById('pageId:formId:txtSearch');         
                txtSearch.focus();
            }
        }

Here Search() is controller method.

Thanks,

Best Answer

There is a difference between how events like keypress and keydown/up are generated in chrome, entering characters will generated all three events (press/up/down) however pressing modifiers (like enter in your case) will generate only keydown and keyup event.

You may have a look at this page for more information as well as at w3schools:

"Modifier keys" are one class of special keys. They include keys like Shift, Control and Alt, that don't send characters, but modify the characters sent by other keys. For nearly all modern browsers, both keydown and keyup events are triggered by modifier keys, but keypress events are not. This is consistent with their being "key" events not "character" events.

There is also a google group discussion

I think you will have to use on keyup/down event for detecting enter in chrome and some other browsers as well.

Related Topic