javascriptc#ascxaspx-user-control

how to call OnTextChanged in asp:TextBox when press any key


I used an asp:Textbox as a search box on the ascx page. Now it works when I press enter after inputting my text. I want to change it to smart search. (when I press a key, the OnTextChanged should call to code behind the function without clicking anywhere or pressing enter key) please help me to achieve this. Thank you

<asp:TextBox ID="SearchBox" runat="server" placeholder="Search" AutoPostback="true" OnTextChanged="SearchBox_TextChanged" ></asp:TextBox>

code behind in ascx page:

protected void SearchBox_TextChanged(object sender, EventArgs e)
{           
     // searching
}

Solution

  • you can use the onkeyup event of the TextBox to call JavaScript function which makes AJAX request to the server to perform the search, to do so, add

    onkeyup="search()"

    to your TextBox:

    <asp:TextBox ID="SearchBox" runat="server" placeholder="Search" onkeyup="search()"></asp:TextBox>
    

    Then call the

    search()

    function

    Javascript:

    function search() 
    {
       var searchTerm = $('#<%=SearchBox.ClientID%>').val();
       $.ajax({
           type: "POST",
           url: "YourPage.aspx/SearchBox_TextChanged",
           data: "{searchTerm: '" + searchTerm + "'}",
           contentType: "application/json; charset=utf-8",
           dataType: "json",
           success: function (response) {
               // Handle success response
           },
           error: function (xhr, status, error) {
               // Handle error response
           }
       });
     }
    

    and finally perform your search in server side and return result:

    C#:

    [System.Web.Services.WebMethod]
    public static string SearchBox_TextChanged(string searchTerm)
    {
       // Perform search and return result as a JSON object
       return JsonConvert.SerializeObject(searchResults);
    }