Reputation: 9063
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?
Upvotes: 0
Views: 356
Reputation: 15413
In ASP.NET, ids generated client side are not those you see in your ASP.NET markup (have a look at the generated source)
You will need to invoke the ClientID
property of your control to access it through javascript or jQuery.
You may try :
function searchKeyPress(e) {
if (typeof e == 'undefined' && window.event) { e = window.event; }
if (e.keyCode == 13) {
document.getElementById('<%=butSearch.ClientID%>').click();
}
}
If you understand how ASP.NET Ids are generated, you may also play with the ClientIDMode of your control, setting it to static.
Upvotes: 1
Reputation: 3625
You can do it like that:
function searchKeyPress(e) {
e = e || window.event;
var key = e.keyCode || e.which;
if (key == 13) {
document.getElementById("butSearch").click();
}
}
Upvotes: 1
Reputation: 53666
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
}
}
}
Upvotes: 3