0

I am using jQuery AutoComplete to fetch results from a DataBase based on the value inputted. The user will then click a search button to tell the page to search for that specific entries details.

I want to get 2 values, the Name and Title. I only want to display the Name to the user, while the page uses the Title as a search criteria.

eg: When a person types in Vehicle, the result will display Vehicle1, Vehicle2 in a list.
When the user clicks on Vehicle1, a hidden box will be issues with the Title, which would be Bike, and such as with Vehicle2, which will issue the hidden box with Car.

I can get the Name to show in the text box properly, but I cannot for the life of me (And after 2 days of searching) bind the Title to a hidden box.

JavaScript:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".tb").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "AutoComplete.asmx/FetchEmailList",
                        data: "{ 'prefix': '" + request.term + "' }",
                        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 {
                                    //value: item.Title,
                                    label: item.Name
                                };
                            }));
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            alert(textStatus);
                        }
                    });
                },
                minLength: 2
            });
        });
    </script>

ASPX Code:

<div class="ui-widget" >
    <asp:TextBox ID="tbAuto" class="tb" runat="server">
    </asp:TextBox>
    <asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>
</div>

CodeBehind:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class AutoComplete : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Employee> FetchEmailList(string prefix)
{
    var emp = new Employee();
    var fetchEmail = emp.GetEmployeeList(prefix)
    .Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));
    return fetchEmail.ToList();
}    
}

CompletionClass: (Excuse the naming)

public class Employee
{
    public string Title { get; set; }
    public string Name { get; set; }
    public string value { get; set; }

    public List<Employee> GetEmployeeList(string prefixText)
    {
        List<Employee> cmpList = new List<Employee>();

        SqlConnection db = DataConn.SqlConnection();

        db.Open();
        SqlTransaction transaction = db.BeginTransaction();

        //var array = new ArrayList();

        try
        {
            SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    cmpList.Add(new Employee() { Name = reader["Value1"].ToString(), Title = "Value1_Cat", value = "Value1_Cat"});
                }
            }

            command = new SqlCommand("Select [something] FROM [somewhere] WHERE [thingy] LIKE N'%" + prefixText + "%' ORDER BY [previousThingy] ASC", db, transaction);
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});
                }
            }

            transaction.Commit();
        }
        catch (SqlException)
        {
            transaction.Rollback();
            cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});
            //array.Add("Problem Getting Results.");
        }

        if (cmpList.Count == 0)
            cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});
        //array.Add("Nothing to Display.");

        //return array;

        return cmpList;
    }

}

2 Answers 2

1

Those modifications to your JavaScript should do the trick:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.0/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('input[name$="tbAuto"]').autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "AutoComplete.asmx/FetchEmailList",
                    data: "{ 'prefix': '" + request.term + "' }",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    dataFilter: function (data) { return data; },
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            minLength: 2,
            focus: function(event, ui) {
                $('input[name$="tbAuto"]').val(ui.item.Name);
                return false;
            },
            select: function(event, ui) {
                $('input[name$="tbAuto"]').val(ui.item.Name);
                $('input[name$="tbHidden"]').val(ui.item.Title);
                return false;
            }
        }).data('autocomplete')._renderItem = function(ul, item) {
            return $('<li>').data('item.autocomplete', item).append('<a>' + item.Name + '</a>').appendTo(ul);
        };
    });
</script>

The assumption here is that the selectors returns exactly the element which we are working on, if not they need to be adjusted.

Sign up to request clarification or add additional context in comments.

15 Comments

Sooo close! I have the 'hidden field' binding to a visible text box. The 'new text box shows the 'Name' (exactly as the old text box) instead of the title. EDIT: Added the .aspx page code..sorry.
Fixed it! I realised that the ID of the aspx controls changed :/ Should of thought of that sooner! I changed the class of the hidden control to td, and $('.td').val(ui.item.Title);... When can I get you a coffee?? :D
@NewAmbition After your update I have changed selectors to more exact ones so the answer will be more usable in future. In the subject of coffee - the mind exercise (and the points:>) is enough :).
@iProgrammer I doubt we can solve this in comments (and we also shouldn't as this is not what comments are for). I need some more contex, source code etc.
@NewAmbition Justice have been served
|
0

Cool. I've been googling for this solution for days... excellent clean code! Just a small remark: using jqueryUI 1.10, this throws javascript exception. .data('autocomplete')._renderItem = function(ul, item) {... I've used .data('ui-autocomplete')._renderItem = function(ul, item) {... and everything works great.

1 Comment

Glad you could get a solution :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.