'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?
Solution 1:[1]
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
}
}
}
Solution 2:[2]
Try instead type="submit" inside input tag.
Solution 3:[3]
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();
}
}
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mike 'Pomax' Kamermans |
Solution 2 | user1390282 |
Solution 3 | |
Solution 4 |