Skip to content
Advertisement

Attempting to make enter button ‘clickable’

I want to make a ‘search’ button clickable upon clicking enter.

This is my html:

<input type="text" runat="server" id="txtSearch" onkeypress="searchKeyPress(event);" 
<input type="button" runat="server" style="padding:5px;" id="butSearch" onserverclick="butSearch_Click" value="Search" disabled/>

This is the JavaScript I am using:

function searchKeyPress(e) { 
  if (typeof e == 'undefined' && window.event) { e = window.event; }
  if (e.keyCode == 13) {
    document.getElementById("butSearch").click();
  }
}

I am however getting an error

‘Uncaught TypeError:Cannot call method click of nul’

Advice perhaps on why I get this error and is there a better alternative at achieving this?

Advertisement

Answer

are those runat="server" required? you get the error because when searchKeyPress gets called, your button doesn’t exist (yet). Either it’s being triggered before DOMContentLoaded, or asp.net is doing funky things with your button, keeping it out of the DOM entirely.

Also some general JavaScript tips:

function searchKeyPress(e) { 
  // a much cleaner "use var, or assign if not defined":
  e = e || window.event;

  // strict comparison:
  if (e.keyCode === 13) {

    // verify we have a button:
    var btn = document.getElementById("butSearch");

    if (btn) {
      btn.click();
    } else {
      // btn does not exist. arbitrary code goes here
    }
  }
}
Advertisement