Link to home
Start Free TrialLog in
Avatar of SRM19
SRM19

asked on

Capturing enter key pressed using javascript.

Hi All,

I am using the following code to capture the enter key pressed.

function enterKeypressHandler(e)
{
      if (!e)
            e = window.event;
            
      if (e.keyCode == 13)
      {
            document.getElementById('<%=btnSearch.ClientID%>').click();
            return false;
      }
            
      return true;
}
document.attachEvent("onkeypress", enterKeypressHandler);

It works fine when I put this script right on the .aspx page.

When put this code in a .js file and call that .js file from .aspx then there is a problem.

This is how I am calling the script in .js file.

<script src="../js/enterKeypressHandler.js" type="text/javascript"></script>

problem is when I type something in a textbox and press enter does not work but if I remove the focus from the textbox then it works.

Can I what is causing the problem.

Any solution in this regard is appreciated.

Thanks,
SRM.
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Hi SRM19,
Perhaps you can amend the js's external link, eg:
<script src="js/enterKeypressHandler.js" type="text/javascript"></script>
Avatar of SRM19
SRM19

ASKER

Hi x com,

I am doing that because the js file and the aspx file are under the same folder. they are in different folders.

Thanks,
SRM.
Hi SRM,
Ok, that's meant your js file is pointing to correct file.
Can you post the js error details here? Perhaps you can put alert("test") to test whether the action has been invoked or not.

function enterKeypressHandler(e)
{
      if (!e)
            e = window.event;
           
      if (e.keyCode == 13)
      {
            alert("test") ;
            document.getElementById('<%=btnSearch.ClientID%>').click();
            return false;
      }
           
      return true;
}

Avatar of SRM19

ASKER

Hi x com,
Thanks for your responses

its definitely going into the javascript. i could get the alert message and then throwed the error

document.getElementById('...').click(); is null or not an object.

the problem  is when select something in a drop down and remove the focus from the drop down then it works. if the focus is still on drop down then it doesnt work.

Any idea why is it doing this.

Thanks,
SRM.
ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial