jQuery 自动完成多个输出 [英] jQuery AutoComplete multiple Output

查看:20
本文介绍了jQuery 自动完成多个输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery AutoComplete 根据输入的值从数据库中获取结果.然后,用户将单击搜索按钮,告诉页面搜索该特定条目的详细信息.

我想获得 2 个值,名称标题.我只想向用户显示名称,而页面使用标题作为搜索条件.

例如:当一个人输入Vehicle时,结果将在列表中显示Vehicle1, Vehicle2.
当用户点击Vehicle1时,隐藏的框将是Title的问题,即Bike,例如Vehicle2,会发出带有Car的隐藏框.

我可以让 Name 正确显示在文本框中,但我一生都无法(并且经过 2 天的搜索)将 Title 绑定到一个隐藏的盒子.

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").自动完成({来源:功能(请求,响应){$.ajax({url: "AutoComplete.asmx/FetchEmailList",数据:{'前缀':'"+ request.term +'}",数据类型:json",类型:POST",contentType: "application/json; charset=utf-8",数据过滤器:函数(数据){返回数据;},成功:功能(数据){响应($.map(data.d,函数(项目){返回 {//值:item.Title,标签:item.Name};}));},错误:函数(XMLHttpRequest,textStatus,errorThrown){警报(文本状态);}});},最小长度:2});});

ASPX 代码:

<asp:TextBox ID="tbAuto" class="tb" runat="server"></asp:TextBox><asp:TextBox runat="server" ID="tbHidden" class="tb"></asp:TextBox>

代码隐藏:

[WebService(Namespace = "http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][脚本服务]公共类自动完成:System.Web.Services.WebService{[网络方法][ScriptMethod(ResponseFormat = ResponseFormat.Json)]公共列表<员工>FetchEmailList(字符串前缀){var emp = 新员工();var fetchEmail = emp.GetEmployeeList(前缀).Where(m => m.Name.ToLower().StartsWith(prefix.ToLower()));返回 fetchEmail.ToList();}}

CompletionClass:(请原谅命名)

公共类员工{公共字符串标题{获取;放;}公共字符串名称 { 获取;放;}公共字符串值 { 获取;放;}公共列表<员工>GetEmployeeList(字符串前缀文本){列表<员工>cmpList = new List();SqlConnection db = DataConn.SqlConnection();db.Open();SqlTransaction 事务 = db.BeginTransaction();//var array = new ArrayList();尝试{SqlCommand command = new SqlCommand("Select [something] FROM vwGetDetails WHERE [something_else] LIKE N'%" + prefixText + "%' ORDER BY [thatOther_thing] ASC", db, transaction);使用 (SqlDataReader reader = command.ExecuteReader()){而 (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);使用 (SqlDataReader reader = command.ExecuteReader()){而 (reader.Read()){cmpList.Add(new Employee() { Name = reader["Value2"].ToString(), Title = "Value2_Cat", value = "Value2_Cat"});}}交易.提交();}捕获(SqlException){事务.回滚();cmpList.Add(new Employee() { Name = "Problem Getting Results.", value = "Error"});//array.Add("问题获取结果.");}如果(cmpList.Count == 0)cmpList.Add(new Employee() { Name = "Nothing to Display.", value = "Info"});//array.Add("没什么可显示的.");//返回数组;返回 cmpList;}}

解决方案

对 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 () {$('input[name$="tbAuto"]').autocomplete({来源:功能(请求,响应){$.ajax({url: "AutoComplete.asmx/FetchEmailList",数据:{'前缀':'"+ request.term +'}",数据类型:json",类型:POST",contentType: "application/json; charset=utf-8",数据过滤器:函数(数据){返回数据;},成功:功能(数据){响应(数据.d);},错误:函数(XMLHttpRequest,textStatus,errorThrown){警报(文本状态);}});},最小长度:2,焦点:功能(事件,用户界面){$('input[name$="tbAuto"]').val(ui.item.Name);返回假;},选择:功能(事件,用户界面){$('input[name$="tbAuto"]').val(ui.item.Name);$('input[name$="tbHidden"]').val(ui.item.Title);返回假;}}).data('autocomplete')._renderItem = function(ul, item) {return $('
  • ').data('item.autocomplete', item).append('' + item.Name + '</a>').appendTo(ul);};});
  • 这里的假设是选择器返回的正是我们正在处理的元素,如果不是,则需要对其进行调整.

    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;
        }
    
    }
    

    解决方案

    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.

    这篇关于jQuery 自动完成多个输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆