Friday, December 6, 2013

How to fix the apostrophe issue in the JQuery AutoComplete control

I recently experienced an issue in which the JQuery AutoComplete control was throwing exceptions when attempting to locate an employee whose last name contained an apostrophe (i.e. O'Brien).  To resolve the issue, I simply added a line of code that replaced the apostrophe character with the proper escape sequence like so:

request.term = request.term.replace("'", "\\'");

Here is the complete function with the new line of code added in the appropriate location:

$("#<%=txtSelectUserName.ClientID %>").autocomplete({
    source: function (request, response) {
        request.term = request.term.replace("'", "\\'");
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/ADGroupManagementWS.asmx/GetAllADUsers",
            data: "{'keywordStartsWith':'" + request.term + "'}",
            dataType: "json",
            async: true,
            success: function (data) {
                response(data.d);
            },
            error: function (result) {
                alert("Due to unexpected errors, data could not be loaded");
            }
        });
    },
    minLength: 1
});