Set TextBox value on jQuery AutoComplete selection using Ajax in ASP.Net

Corobori
 
on Jan 29, 2021 10:33 PM
Sample_752325.zip
1879 Views

Hi,

A few months ago you solve my issue in Apply custom style (CSS) to AutoComplete TextBox results using jQuery in ASP.Net

I bumped into a new issue. 

To match my real-life sample see below your code that I altered a little bit. If you look at picture you see that when selecting an element the selected item doesn't show up as expected, meaning that the title comes with _ before when actually I would like to have the name only

To your code I changed the part written in orange below. I tried adding this statement 

$("[id$=txtSearch]").val(i.item.label.split('_')[0]);

in the select section but it didn't work 

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js"></script>
<link rel="Stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<style type="text/css">
    .labelText {
        color: red;
        float: left;
        font-family: Courier New;
        font-size: 10pt;
    }
 
    .valueText {
        float: right;
        background-color: aqua;
        font-family: Courier New;
        font-size: 10pt;
    }
 
    .dvDetails {
        padding: 5px;
        width: 235px;
        height: 30px;
    }
</style>
<script type="text/javascript">
    $(function () {
        $("[id$=txtSearch]").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Default.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("[id$=hfCustomerId]").val(i.item.val);
            },
            minLength: 1
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
               var div = $("<li>")
                   .append("<a class='dvDetails'><span class='labelText'>" + item.label.split('_')[0] +
                       "</span><span class='valueText'>(" + item.label.split('_')[1] + ")</span></a>")
                   .appendTo(ul);
               return div; 
        };
    });
</script>
Enter search term:
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />

 

    <WebMethod()>
    Public Shared Function GetCustomers(prefix As String) As String()
        Dim customers As New List(Of String)()
        Using conn As New SqlConnection()
            conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
            Using cmd As New SqlCommand()
                cmd.CommandText = "select ContactName, CustomerId,ContactTitle from Customers where ContactName like @SearchText + '%'"
                cmd.Parameters.AddWithValue("@SearchText", prefix)
                cmd.Connection = conn
                conn.Open()
                Using sdr As SqlDataReader = cmd.ExecuteReader()
                    While sdr.Read()
                        customers.Add(String.Format("{0}-{1}", sdr("ContactName") & "_" & sdr("ContactTitle"), sdr("CustomerId")))
                    End While
                End Using
                conn.Close()
            End Using
        End Using
        Return customers.ToArray()
    End Function

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 30, 2021 01:20 AM

Hi Corobori,

Using the below article i have created the example.

Implement jQuery AutoComplete TextBox from database using AJAX PageMethods in ASP.Net

Check this example. Now please take its reference and correct your code.

HTML

<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.0.min.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/jquery-ui.min.js"></script>
<link rel="Stylesheet" type="text/css" href="https://ajax.aspnetcdn.com/ajax/jquery.ui/1.9.2/themes/blitzer/jquery-ui.css" />
<style type="text/css">
    body {
        font-family: Arial;
        font-size: 10pt;
    }

    .labelText {
        color: red;
        float: left;
        font-family: Courier New;
        font-size: 10pt;
    }

    .valueText {
        float: right;
        background-color: aqua;
        font-family: Courier New;
        font-size: 10pt;
    }

    .dvDetails {
        padding: 5px;
        width: 350px;
        height: 30px;
    }
</style>
<script type="text/javascript">
    $(function () {
        $("[id$=txtSearch]").autocomplete({
            minLength: 1,
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/VB.aspx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    }
                });
            },
            select: function (e, i) {
                $(this).val(i.item.label.split('_')[0]);
                $("[id$=hfCustomerId]").val(i.item.val);
                return false;
            }
        }).data("ui-autocomplete")._renderItem = function (ul, item) {
            var div = $("<li>")
                .append("<a class='dvDetails'><span class='labelText'>" + item.label.split('_')[0] +
                    "</span><span class='valueText'>(" + item.label.split('_')[1] + ")</span></a>")
                .appendTo(ul);
            return div;
        };
    });
</script>
<asp:TextBox ID="txtSearch" runat="server" />
<asp:HiddenField ID="hfCustomerId" runat="server" />
<asp:Button ID="Button1" Text="Submit" runat="server" OnClick="Submit" />

Namespaces

C#

using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

VB.Net

Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Services

Code

C#

[WebMethod]
public static string[] GetCustomers(string prefix)
{
    List<string> customers = new List<string>();
    using (SqlConnection conn = new SqlConnection())
    {
        conn.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT ContactName, CustomerId, ContactTitle FROM Customers WHERE ContactName LIKE @SearchText + '%'";
            cmd.Parameters.AddWithValue("@SearchText", prefix);
            cmd.Connection = conn;
            conn.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                while (sdr.Read())
                {
                    customers.Add(
                        string.Format("{0}_{1}-{2}",
                        sdr["ContactName"].ToString().Trim(),
                        sdr["ContactTitle"].ToString().Trim(),
                        sdr["CustomerId"]));
                }
            }
            conn.Close();
        }
    }
    return customers.ToArray();
}


protected void Submit(object sender, EventArgs e)
{
    string customerName = Request.Form[txtSearch.UniqueID];
    string customerId = Request.Form[hfCustomerId.UniqueID];
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Name: " + customerName.Replace("'","\\'") + "\\nID: " + customerId + "');", true);
}

VB.Net

<WebMethod()>
Public Shared Function GetCustomers(prefix As String) As String()
    Dim customers As New List(Of String)()
    Using conn As New SqlConnection()
        conn.ConnectionString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using cmd As New SqlCommand()
            cmd.CommandText = "SELECT ContactName, CustomerId, ContactTitle FROM Customers WHERE ContactName LIKE @SearchText + '%'"
            cmd.Parameters.AddWithValue("@SearchText", prefix)
            cmd.Connection = conn
            conn.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                While sdr.Read()
                    customers.Add(
                        String.Format("{0}_{1}-{2}",
                        sdr("ContactName").ToString().Trim(),
                        sdr("ContactTitle").ToString().Trim(),
                        sdr("CustomerId")))
                End While
            End Using
            conn.Close()
        End Using
    End Using
    Return customers.ToArray()
End Function

Protected Sub Submit(sender As Object, e As EventArgs)
    Dim customerName As String = Request.Form(txtSearch.UniqueID)
    Dim customerId As String = Request.Form(hfCustomerId.UniqueID)
    ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Name: " & customerName.Replace("'", "\'") & "\nID: " & customerId & "');", True)
End Sub

Screenshot