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

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

问题描述

我使用jQuery自动完成获取基于输入的值从数据库中的结果。然后,用户会点击搜索按钮来告诉页面来搜索特定条目的详细信息。

我想获得2个值,在名称标题即可。我只是想显示的名称给用户,而页面使用的标题作为搜索条件。

例如:当一个人类型的汽车后,结果将显示 Vehicle1,Vehicle2 列表中的结果
当用户点击 Vehicle1 ,一个隐框将与在标题后,这将是自行车,以及诸如与 Vehicle2 ,这将发出

的隐框

我可以在名称在文本框中显示正常,但我不能为我的生活(2天后搜索的)绑定在标题以一个隐藏的框。

JavaScript的:

 <脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/jquery-1.8.2.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/ui/1.9.0/jquery-ui.js>< / SCRIPT>
    <脚本类型=文/ JavaScript的>
        $(文件)。就绪(函数(){
            $(TB)。自动完成({
                来源:函数(请求,响应){
                    $阿贾克斯({
                        网址:AutoComplete.asmx / FetchEmailList
                        数据:{'preFIX':'+ request.term +'},
                        数据类型:JSON
                        键入:POST,
                        的contentType:应用/ JSON的;字符集= UTF-8,
                        dataFilter:功能(数据){返回数据; },
                        成功:功能(数据){
                            响应($。图(data.d,函数(项目){
                                返回{
                                    //值:item.Title,
                                    标签:item.Name
                                };
                            }));
                        },
                        错误:功能(XMLHtt prequest,textStatus,errorThrown){
                            警报(textStatus);
                        }
                    });
                },
                的minLength:2
            });
        });
    < / SCRIPT>

ASPX code:

 < D​​IV CLASS =UI窗口小部件>
    < ASP:文本框ID =tbAuto级=TB=服务器>
    < / ASP:文本框>
    < ASP:文本框=服务器ID =tbHidden级=TB>< / ASP:文本框>
< / DIV>

codeBehind:

  [WebService的空间(namespace =htt​​p://tempuri.org/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)
[ScriptService]
公共类自动完成:System.Web.Services.WebService
{
[的WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)
公开名单<员工> FetchEmailList(字符串preFIX)
{
    VAR EMP =新员工();
    VAR fetchEmail = emp.GetEmployeeList(preFIX)
    。凡(M =方式> m.Name.ToLower()StartsWith(prefix.ToLower()));
    返回fetchEmail.ToList();
}
}

CompletionClass:(对不起命名)

 公共类Employee
{
    公共字符串名称{搞定;组; }
    公共字符串名称{;组; }
    公共字符串值{获得;组; }    公开名单<员工> GetEmployeeList(字符串prefixText)
    {
        清单<员工> cmpList =新的List<员工>();        的SqlConnection分贝= DataConn.SqlConnection();        db.Open();
        交易的SqlTransaction = db.BeginTransaction();        // VAR阵列=新的ArrayList();        尝试
        {
            的SqlCommand命令=新的SqlCommand(选择[东西] FROM vwGetDetails WHERE [something_else] LIKE N'%+ prefixText +%'ORDER BY [thatOther_thing] ASC,数据库,交易);
            使用(SqlDataReader的读卡器= Command.ExecuteReader却())
            {
                而(reader.Read())
                {
                    cmpList.Add(新员工(){名称=读卡器[值1]的ToString(),标题=Value1_Cat,值=Value1_Cat});
                }
            }            命令=新的SqlCommand(选择[东西] FROM [地方],其中[啄] LIKE N'%+ prefixText +%'ORDER BY [previousThingy] ASC,数据库,交易);
            使用(SqlDataReader的读卡器= Command.ExecuteReader却())
            {
                而(reader.Read())
                {
                    cmpList.Add(新员工(){名称=读卡器[值2]的ToString(),标题=Value2_Cat,值=Value2_Cat});
                }
            }            器transaction.commit();
        }
        赶上(SQLEXCEPTION)
        {
            transaction.Rollback();
            cmpList.Add(新员工(){名称=问题得到结果。,值=错误});
            //array.Add(\"Problem获取结果)。
        }        如果(cmpList.Count == 0)
            cmpList.Add(新员工(){名称=没有要显示,值=信息});
        //array.Add(\"Nothing,显示)。        //返回数组;        返回cmpList;
    }}


解决方案

这些修改到你的JavaScript应该做的伎俩:

 <脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/jquery-1.8.2.js>< / SCRIPT>
<脚本类型=文/ JavaScript的SRC =HTTP://$c$c.jquery.com/ui/1.9.0/jquery-ui.js>< / SCRIPT>
<脚本类型=文/ JavaScript的>
    $(文件)。就绪(函数(){
        $(输入[名称$ =tbAuto]')。自动完成({
            来源:函数(请求,响应){
                $阿贾克斯({
                    网址:AutoComplete.asmx / FetchEmailList
                    数据:{'preFIX':'+ request.term +'},
                    数据类型:JSON
                    键入:POST,
                    的contentType:应用/ JSON的;字符集= UTF-8,
                    dataFilter:功能(数据){返回数据; },
                    成功:功能(数据){
                        响应(data.d);
                    },
                    错误:功能(XMLHtt prequest,textStatus,errorThrown){
                        警报(textStatus);
                    }
                });
            },
            的minLength:2,
            重点:函数(事件,UI){
                $(输入[名称$ =tbAuto])VAL(ui.item.Name)。
                返回false;
            },
            选择:函数(事件,UI){
                $(输入[名称$ =tbAuto])VAL(ui.item.Name)。
                $(输入[名称$ =tbHidden])VAL(ui.item.Title)。
                返回false;
            }
        })。数据(自动完成)._ renderItem =功能(UL,项目){
            返回$('<李>')的数据(item.autocomplete,项目).append('< A>'+ item.Name +'< / A>')。appendTo(UL);
        };
    });
< / SCRIPT>

这里的假设是,选择器返回到底是哪我们正在处理的元件,如果不是他们需要进行调整。

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天全站免登陆