Adding an autocomplete textbox using JavaScript

#1

Overview

Thanks to jQuery UI, you can use a combination of JavaScript and C# code to set a textbox with an autocomplete filter.

Autocomplete%20result

Example

You can download the TEXTBOX_AUTOCOMPLETE process as an example.

How it works

To create the autocomplete filter, we used jQuery UI’s Autocomplete widget.

To get the filtered list content, we execute a SQL query in the code-behind. The results will be formatted in JavaScript array format and set in a hidden field (REQUEST_USER_LIST)

private void GetUser()
{
    string queryString = "SELECT CONCAT(LASTNAME,' ',FIRSTNAME) as name, USERNAME FROM USERS";
    string queryJs = "[";
    using(System.Data.SqlClient.SqlConnection sqlConnection = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["MainDbSource"].ToString()))
    {
        System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(queryString, sqlConnection);
        sqlConnection.Open();
            using (System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader())
            {
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        queryJs = queryJs + "{ value :'" + reader[0].ToString() +
                            "', login :'" + reader[1].ToString() + "'},";
                    }
                    queryJs.Substring(queryJs.Length-1);
                }
                queryJs += "]";
            }
        sqlConnection.Close();
        }

    REQUEST_USER_LIST.Text = queryJs;
}

To add the JavaScript code, go to the Web References tab in the Form configuration panel.

Find%20js%20code

Code example

This example gets the value of the hidden REQUEST_USER_LIST field, and transforms this into a JavaScript array.

if(typeof $selectedObject === "undefined") {
    $(function() {

    $("#REQUEST_ROW_USER_LIST").hide()
       var array = eval($("#REQUEST_USER_LIST").val());

        $('#REQUEST_FILTER').autocomplete({
            source : array,

             select : function(event, ui){ // When a selection is done
                $('#REQUEST_LOGIN').val(ui.item.login); // we add login in the specific field
            }
        });
    })
}
0 Likes