简体   繁体   中英

jquery asp.net, stopping postback

I have a text box and I want the user to be able to type in the TextBox and when they hit enter, I want jQuery to make a ajax call to a web method.
The problem is, when user hits the enter, the method is called but then the page refreshes due to the return. I've tried using return false but with no results.

Here is the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="X-UA-Compatible" content="IE=7" />  
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script language="javascript">
   function serviceCall(getText) {          
      $.ajax({
       type: "POST",
       url: 'ActiveDirectoryAutoFillWebService.asmx/TestMethod',
       data: "{'getId':'+ getText +'}",
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (msg) {
       $("#divResult").html(msg.d);
       },
       error: function (e) {
       $("#divResult").html("WebSerivce unreachable " + e.name + " " + e.message);
     }
   });  
  //  return false;       This does not work      
}
function searchKeyPress(e) {
   if (typeof e == 'undefined' && window.event) { e = window.event; }
       if (e.keyCode == 13) {              
           serviceCall(e)   
           //  return false;       This does not work         
       }          
 }
 </script>
</head>
<body>

<form id="form1" runat="server">      
    <div id="divResult" style="margin-top: 20px;"></div>
    <asp:TextBox ID="tbSearchName" runat="server" onKeyPress="searchKeyPress(event); "></asp:TextBox>      

</form>
</body>
</html>

If anyone knows how I can accomplish this, please let me know.

Have a look at the following functions on the event object:

In your case, you can use

e.preventDefault()

This will stop the default action from happening.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM