ASP.NET (35) SQL (25) JAVASCRIPT (24) HTML (14) STYLE SHEET (6) ASP (4) SCRIPT (1)

Search me out HERE!!

Autofill textbox with Ajax along with value

See below steps to Autofill textbox with Ajax with list of items along with value. Also value will be fetched once any of item is selected from list.

1. Add onkeyup event on textbox to autofill textbox as user start typing in textbox.

onkeyup=KeyUpEvent('txtSearch','1');


2. Add below javascript method which will be called on keyup event of textbox. This method will be used to make Ajax call and get item list with value.

function KeyUpEvent(txtBoxId, id) {
    try {
        if (txtBoxId != null) {
            $("#" + txtBoxId).autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: 'PageName.aspx/ListItemKeyValue',
                        data: "{'prefix':'" + $('#' + txtBoxId).val() + "','Parameter1':'" + id + "'}",
                        dataType: "json",
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        dataFilter: function (data) { return data; },
                        success: function (data) {
                            response($.map(data.d, function (item) {
                                return {
                                   label: item.split('/')[0],
                                   val: item.split('/')[1]
                                }
                            }))
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                        }
                    });
                },

                select: function (event, ui) { alert(ui.item.val); return false; },
                minLength: 3
            });
        }
    }
    catch (e) {
       alert('Error: ' + e);
    }
}


3. Write below web method in .cs file of page to fetch item from database based on value passed from Javascript method.

[WebMethod]
public string[] ListItemKeyValue(string prefix, int Parameter1)
{
    List items;
    Data objData = new Data();
   
//Fetch data into Datatable    System.Data.DataTable dt = objData.GetListItemKeyValue(Parameter1, prefix).Tables[0];
    items = new List(dt.Rows.Count);
    for (int intI = 0; intI < items.Capacity; intI++)
    {
       items.Add(string.Format("{0}/{1}", dt.Rows[intI]["Name"].ToString(), dt.Rows[intI]["Value"].ToString()));
    }
    return items.ToArray();
}

1 comment: