tags:

views:

423

answers:

2

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  A: 
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)"
Kevin
+6  A: 

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.

tj111
Alternatively `arguments[0]`.
Gumbo
Also, you'll want it to work in IE. So e = e || window.event;
J-P