Sunday 11 January 2015

AutoComplete extender implementation from client side

AutoComplete extender is one of the way to implement the Auto complete feature to a textbox.

With the below approaches you can get the idea, how can we implement the autocomplete extender differently and different scenarios and functionalities related to the Extender.

The default way of implementation:

<asp:AutoCompleteExtender
                            ID="AutoCompleteExtender1"
                            TargetControlID="uxTxtAddress"
                            runat="server"
                            BehaviorID="AutoCompleteEx"
                            ServiceMethod="GetAddressList"
                            CompletionInterval="1000"
                            MinimumPrefixLength="6"
                            EnableCaching="true"
                            UseContextKey="True"
                            OnClientItemSelected="getSelected">
                        </asp:AutoCompleteExtender>

Alternative way to implement from dynamically from client side using jQuery/javascript:

$create(Sys.Extended.UI.AutoCompleteBehavior, { "delimiterCharacters""""id""AutoCompleteEx""minimumPrefixLength": 6, "serviceMethod""GetAddressList""servicePath""/checkout/payment.aspx""useContextKey"true }, { "itemSelected": getSelected }, null, $get(jQuery("[id$=uxTxtAddress]").attr("id")));

Call this function in document.ready function.

Here we need to pass textbox id, client side selected event and server side service method.

Dispose the behaviour from client-side:

//"AutoCompleteEx" is the behaviour id

if ($find("AutoCompleteEx") != null) {
        $find("AutoCompleteEx").dispose();
    }

Server method:

[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetAddressList(string prefixText, int count, string contextKey)
    {
        return AddressUtility.GetAddressesFromService(prefixText);
    }

Client method after selecting the item from the list:

function getSelected(sender, e) {
    alert(e.get_value());//Gets the value of the selected item
}

A way to stop the default Enter button while selecting an item: 

Call the "trapEnter(e)" function from onkeypress event of the textbox.

function trapEnter(e) {
    e = e || window.event;
    var code = e.keyCode || e.which;
    if (code == 13) {
        cancelEvent(e);
        return false;
    } else {
        return true;
    }
}
 
function cancelEvent(e) {
    e = e ? e : window.event;
    if (e.stopPropagation)
        e.stopPropagation();
    if (e.preventDefault)
        e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}