1

I call a javascript function from a textbox by using OnKeyPress="clickSearchButton()"

Here is my function:

function clickSearchButton()
{
  var code = e.keyCode || e.which;
  var btnSearch = document.getElementById("TopSubBanner1_SearchSite1_btnSearchSite");
  if(code == 13);
      {          
           btnSearch.click(); 
           return false; 
      } 
}

My problem is that this function fires when the user hits the enter button in any textbox, not just the one that calls the function. What am I missing?

EDIT: Still not working correctly. So I'll throw my HTML out there if that helps.

<input name="TopSubBanner1:SearchSite1:txtSearch" type="text" id="TopSubBanner1_SearchSite1_txtSearch" OnKeyPress="clickSearchButton(this)" /><input type="submit" name="TopSubBanner1:SearchSite1:btnSearchSite" value="Search" id="TopSubBanner1_SearchSite1_btnSearchSite" />

Also, this is an ASP.NET page if that makes a difference.

4
  • 1
    How are you connecting your clickSearchButton function to the OnKeyPress event? Commented May 15, 2009 at 16:36
  • You should change the title of this to not be so vague. At least mention the keypress event. Commented May 15, 2009 at 17:19
  • 1
    You shouldn't be passing 'this' to your handler. Commented May 15, 2009 at 17:33
  • Thanks J-P. Is there anything I should be passing in? Commented May 15, 2009 at 17:48

2 Answers 2

6

The event is by default passed as an argument to your function, but your not capturing it as a parameter. If you capture it, the above should work correctly.

function clickSearchButton(e)
{
   e = e || window.event //for IE compliane (thanks J-P)
   //etc

or

function clickSearchButton()
{
   var e = arguments[0];
   e = e || window.event;

Also you have an extra semicolon as Kevin pointed out.

Sign up to request clarification or add additional context in comments.

2 Comments

Alternatively arguments[0].
Also, you'll want it to work in IE. So e = e || window.event;
4
function clickSearchButton(e)
{
  var code;

if(window.event)
    code = e.keyCode;
else
   code = e.which;

var btnSearch = document.getElementById("TopSubBanner1_SearchSite1_btnSearchSite");
  if(code == 13)
      {          
           btnSearch.click(); 
           return false; 
      } 
}

and your calling method should be:

onkeypress="clickSearchButton(event)"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.