attempting to make enter button 'clickable'

谁说胖子不能爱 提交于 2019-12-13 04:32:48

问题


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

'Uncuaght TypeError:Cannot call method click of nul'

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


回答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
    }
  }
}



回答2:


Try instead type="submit" inside input tag.




回答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();
    }
}



回答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.



来源:https://stackoverflow.com/questions/17089289/attempting-to-make-enter-button-clickable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!