Jquery ui 自动完成用 ID 填充隐藏字段

发布于 2024-11-05 06:56:00 字数 5640 浏览 1 评论 0原文

我正在尝试让自动完成插件在一个文本框中填充大学名称,在另一个文本框中填充大学代码。下面的代码返回结果并填充大学名称文本框,但我不知道如何填充另一个输入。

我尝试按照此示例进行操作,但是跨越问题甚至调用网络方法。一件奇怪的事情是,似乎 ajax 是在自动完成附加到用户键入的文本框之前调用的。不确定是什么触发了 js 调用自动完成方法。

我必须将上面的部分与使用 json 自动完成的 jquery ui 文档结合起来(链接)。但我仍然不知道如何像第一个示例一样填充第二个输入。

有什么想法吗?

这是 jquery 和 html

<script language="javascript" type="text/javascript">
    $(function () {
        $("#university").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    url: "AutoComplete.asmx/GetUniversities",
                    dataType: "json",
                    data: "{ 'data': '" + request.term + "' }",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {                                    
                                value: item.Descr,
                                UnivCode: item.UnivCode

                            }                                
                        }));
                    }
                });
            } 
        });          
    });
</script>
<div class="ui-widget"> 
    <label for="university">University: </label> 
    <input id="university" type="text"/> 
    <label for="universityID">ID: </label> 
    <input id="universityID" type="text" /> 
</div> 

这是我的 .net webmethod

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Text;
using System.Data;

[ScriptService()]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class AutoComplete : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<University> GetUniversities(string data)
    {
        List<University> UniversityList = new List<University>();

        try
        {
            clsDataBase db = new clsDataBase();
            DataTable dt = new DataTable();
            StringBuilder sql = new StringBuilder();
            Dictionary<string, object> parms = new Dictionary<string, object>();

            sql.Append(" SELECT univ_code ");
            sql.Append(" , INITCAP(univ_desc) AS descr ");
            sql.Append(" FROM lk_university ");
            sql.Append(" WHERE UPPER(univ_desc) LIKE UPPER(?) ");
            sql.Append(" ORDER BY univ_desc  ");
            parms.Add("university", "%" + data + "%");

            dt = db.executeParmQuery(sql.ToString(), parms);
            DataView dv = new DataView(dt);


            ArrayList filteredList = new ArrayList();

            foreach (DataRowView drv in dv)
            {
                University university = new University();
                university.UnivCode= drv["univ_code"].ToString();
                university.Descr = drv["descr"].ToString();

                UniversityList.Add(university);
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
            //return null;
        }
        //}
        return UniversityList;
    }


    public class University
    {        
        string _value;
        public string value
        {
            get { return _Descr + " (" + _UnivCode + ")"; }            
        }

        string _Descr;
        public string Descr
        {
            get { return _Descr; }
            set { _Descr = value; }
        }

        string _UnivCode;
        public string UnivCode
        {
            get { return _UnivCode; }
            set { _UnivCode = value; }
        }
    }
}

编辑

我能够通过添加 select 事件来使其工作。在我之前的测试中,我把它放在那里,但在错误的位置(最初嵌套在成功事件中)。还必须在成功事件中添加设置值的三行:item.Descr、 Descr: item.Descr 和 UnivCode: item.UnivCode。我不太明白它们引用了什么或它们在做什么,因为输入的实际设置是在 select 事件中完成的,我在其中指定了输入的实际 id ($('#university').val(ui .item.Descr);),但这是让代码正常工作所必需的。

这是工作中的 jquery,没有对 html 或 .net 代码进行任何其他更改。

<script language="javascript" type="text/javascript">
    $(function () {
        $("#university").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    url: "AutoComplete.asmx/GetUniversities",
                    dataType: "json",
                    data: "{ 'data': '" + request.term + "' }",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                value: item.Descr,
                                Descr: item.Descr,
                                UnivCode: item.UnivCode
                            }
                        }));
                    }
                });
            },
            select: function (event, ui) {
                $('#university').val(ui.item.Descr);
                $('#universityID').val(ui.item.UnivCode);                    
                return false;
            }
        });
    });

I'm trying to get the autocomplete plugin to populate one textbox with the university name and another with the university code. The code below returns results and populates the university name textbox, but I can't figure out how to populate another input.

I've tried following this example, but came across problems to even call the webmethod. One odd thing about this was that it seemed that the ajax was called before the autocomplete was attached to the textbox where the user types. Not sure what was triggering the js to call the autocomplete method.

I had to combine parts from the above with the jquery ui doc on autocomplete using json (link). But I still don't know how to get the second input to be populated as in the first example.

any ideas?

Here's the jquery and html

<script language="javascript" type="text/javascript">
    $(function () {
        $("#university").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    url: "AutoComplete.asmx/GetUniversities",
                    dataType: "json",
                    data: "{ 'data': '" + request.term + "' }",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {                                    
                                value: item.Descr,
                                UnivCode: item.UnivCode

                            }                                
                        }));
                    }
                });
            } 
        });          
    });
</script>
<div class="ui-widget"> 
    <label for="university">University: </label> 
    <input id="university" type="text"/> 
    <label for="universityID">ID: </label> 
    <input id="universityID" type="text" /> 
</div> 

Here's my .net webmethod

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections.Generic;
using System.Web.Script.Services;
using System.Text;
using System.Data;

[ScriptService()]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

public class AutoComplete : System.Web.Services.WebService
{

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<University> GetUniversities(string data)
    {
        List<University> UniversityList = new List<University>();

        try
        {
            clsDataBase db = new clsDataBase();
            DataTable dt = new DataTable();
            StringBuilder sql = new StringBuilder();
            Dictionary<string, object> parms = new Dictionary<string, object>();

            sql.Append(" SELECT univ_code ");
            sql.Append(" , INITCAP(univ_desc) AS descr ");
            sql.Append(" FROM lk_university ");
            sql.Append(" WHERE UPPER(univ_desc) LIKE UPPER(?) ");
            sql.Append(" ORDER BY univ_desc  ");
            parms.Add("university", "%" + data + "%");

            dt = db.executeParmQuery(sql.ToString(), parms);
            DataView dv = new DataView(dt);


            ArrayList filteredList = new ArrayList();

            foreach (DataRowView drv in dv)
            {
                University university = new University();
                university.UnivCode= drv["univ_code"].ToString();
                university.Descr = drv["descr"].ToString();

                UniversityList.Add(university);
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
            //return null;
        }
        //}
        return UniversityList;
    }


    public class University
    {        
        string _value;
        public string value
        {
            get { return _Descr + " (" + _UnivCode + ")"; }            
        }

        string _Descr;
        public string Descr
        {
            get { return _Descr; }
            set { _Descr = value; }
        }

        string _UnivCode;
        public string UnivCode
        {
            get { return _UnivCode; }
            set { _UnivCode = value; }
        }
    }
}

EDIT

I was able to get it working by adding the select event. In my previous testing I had it in there, but in the wrong spot (initially nested in the success event). Also had to add the three lines in the success event that set value: item.Descr, Descr: item.Descr, and UnivCode: item.UnivCode. I don't quite understand what these are referencing or what they're doing, since the actual setting of inputs is done in the select event where I specify the actual id's of the inputs ($('#university').val(ui.item.Descr);), but this was needed to get the code to work.

Here's the working jquery without any other changes to the html or the .net code.

<script language="javascript" type="text/javascript">
    $(function () {
        $("#university").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    url: "AutoComplete.asmx/GetUniversities",
                    dataType: "json",
                    data: "{ 'data': '" + request.term + "' }",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data, function (item) {
                            return {
                                value: item.Descr,
                                Descr: item.Descr,
                                UnivCode: item.UnivCode
                            }
                        }));
                    }
                });
            },
            select: function (event, ui) {
                $('#university').val(ui.item.Descr);
                $('#universityID').val(ui.item.UnivCode);                    
                return false;
            }
        });
    });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

韬韬不绝 2024-11-12 06:56:00

我能够通过添加选择事件来使其工作。在我之前的测试中,我把它放在那里,但在错误的位置(最初嵌套在成功事件中)。还必须在成功事件中添加设置值的三行:item.Descr、 Descr: item.Descr 和 UnivCode: item.UnivCode。我不太明白它们引用了什么或它们在做什么,因为输入的实际设置是在 select 事件中完成的,我在其中指定了输入的实际 id ($('#university').val(ui .item.Descr);),但这是让代码正常工作所必需的。

这是工作中的 jquery,没有对 html 或 .net 代码进行任何其他更改。

$(function () {
    $("#university").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: "AutoComplete.asmx/GetUniversities",
                dataType: "json",
                data: "{ 'data': '" + request.term + "' }",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            value: item.Descr,
                            Descr: item.Descr,
                            UnivCode: item.UnivCode
                        }
                    }));
                }
            });
        },
        select: function (event, ui) {
            $('#university').val(ui.item.Descr);
            $('#universityID').val(ui.item.UnivCode);                    
            return false;
        }
    });
});

I was able to get it working by adding the select event. In my previous testing I had it in there, but in the wrong spot (initially nested in the success event). Also had to add the three lines in the success event that set value: item.Descr, Descr: item.Descr, and UnivCode: item.UnivCode. I don't quite understand what these are referencing or what they're doing, since the actual setting of inputs is done in the select event where I specify the actual id's of the inputs ($('#university').val(ui.item.Descr);), but this was needed to get the code to work.

Here's the working jquery without any other changes to the html or the .net code.

$(function () {
    $("#university").autocomplete({
        source: function (request, response) {
            $.ajax({
                type: "POST",
                url: "AutoComplete.asmx/GetUniversities",
                dataType: "json",
                data: "{ 'data': '" + request.term + "' }",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data, function (item) {
                        return {
                            value: item.Descr,
                            Descr: item.Descr,
                            UnivCode: item.UnivCode
                        }
                    }));
                }
            });
        },
        select: function (event, ui) {
            $('#university').val(ui.item.Descr);
            $('#universityID').val(ui.item.UnivCode);                    
            return false;
        }
    });
});
醉酒的小男人 2024-11-12 06:56:00

我在使用 MVC 时经历了这种痛苦,您返回的对象需要有一个 label 属性(显示在下拉列表中)和一个 value 属性(实际选择值 - UnivCode)。

它的关键是在自动完成框中定义一个 select 方法,该方法接受 2 个参数(例如 select: function(e, ui){ ... do stuff ...; return false; })。这里的技巧是返回 false 以防止 jQuery 运行默认事件处理程序。

然后,您可以使用 ui.item.label 获取显示值,并使用 ui.item.value 获取代码。

我使用了一种单独的方法来接受 ui.item,然后将值写入隐藏的输入。

如果我可以将我的代码放在一起,我将发布一个示例。

例子:-
此示例使用名为 Autocomp1_display 的文本框,自动完成功能附加到该文本框。然后,displayItem 方法将所选项目的显示值写入此文本框,并将所选值放入隐藏范围中。

$j("#Autocomp1_display").autocomplete({
source: function(request, response){
    $j.ajaxSetup({cache: false});
    $j.ajax({
        url: "AutoComplete.asmx/GetUniversities"
            type: "GET",
        data: request,
        dataType: "json",
        success: function (data) {
            request.term="";
            response(data);
        }
    });
},
cache: false,
select: function(e, ui){
    displayItem("Autocomp1", ui.item);
    Autocomp1_HasSelections = true;
    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
    $j('#Autocomp1').change();
    return false;
},
focus: function(event, ui){
    if (ui.item.label){
        $j(this).val(ui.item.label);
    } else {
        $j(this).val(ui.item.value);
    }
    return false;
}
});

select 事件使用如下的 displayItem 方法

//Function to write the entries into the text box
function displayItem(target, dataObject) {
    var displayValue = dataObject.label.replace('\n','');

    var existingSpan = false;

    existingSpan = document.getElementById("span_" + displayValue);

    if (!existingSpan) {
        var span = $j("<span>").text(displayValue); //Create a new span tag to display the selected value
        span.attr({ id: "span_" + dataObject.value });
        var hiddenFld = $j("<input>").attr({ type: "hidden" }).val(dataObject.value); //Create a div object to store the code value
        hiddenFld.addClass(target + "IdField").css("visibility", "hidden").css("height", 0).attr({ id: target, name: target }); //Format the div
        var a = $j("<a>").addClass(target + "remove").attr({
            href: "javascript:",
            title: "Remove " + displayValue
        }).text("x").appendTo(span); //Define the "x" to remove the span

        hiddenFld.appendTo(span); //Append the div to the span
        span.insertBefore("#" + target + "_display"); //Insert span before the concealed text box
        $j("#" + target).attr({ value: dataObject.value }); //Store the ID value related to the selected item
        $j("#" + target + "_display").val("").css("top", 2); //Store the ID value related to the selected item
        //$j("#" + target + "_display").flushCache(); //Flush the cache for the autocomplete control
    } else {
        alert("This item has already been selected");
    }
}

setAutocompleteState 方法: -

function setAutocompleteState(targetName, IsMultiSelect, HasSelections) {
    if (!IsMultiSelect && HasSelections) {
        $j("#" + targetName).autocomplete("option", "disabled", true);
    } else {
        $j("#" + targetName).autocomplete("option", "disabled", false);
    }
}

isMultiSelect 和 HasSelections 定义是否应启用自动完成,targetName 只是已“自动完成”的文本框的 ID

I have been through this pain using MVC and the object that you return needs to have a label property (displayed in the drop down list) and a value property (the actual selection value - UnivCode).

The key to it is having a select method defined on your autocomplete box that accepts 2 arguments (e.g. select: function(e, ui){ ... do stuff ...; return false; }). The trick here is the return false to prevent jQuery from running the default event handler.

You can then use ui.item.label to get the display value, and ui.item.value to get the code.

I used a separate method that accepted ui.item and then wrote the values to hidden inputs.

If I can get my code together, I will post an example.

Example:-
This example is using a text box called Autocomp1_display to which the autocomplete is attached. The displayItem method then writes the display value of the selected item to this text box, and puts the selected value into a hidden span.

$j("#Autocomp1_display").autocomplete({
source: function(request, response){
    $j.ajaxSetup({cache: false});
    $j.ajax({
        url: "AutoComplete.asmx/GetUniversities"
            type: "GET",
        data: request,
        dataType: "json",
        success: function (data) {
            request.term="";
            response(data);
        }
    });
},
cache: false,
select: function(e, ui){
    displayItem("Autocomp1", ui.item);
    Autocomp1_HasSelections = true;
    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
    $j('#Autocomp1').change();
    return false;
},
focus: function(event, ui){
    if (ui.item.label){
        $j(this).val(ui.item.label);
    } else {
        $j(this).val(ui.item.value);
    }
    return false;
}
});

The select event makes use of the displayItem method as below

//Function to write the entries into the text box
function displayItem(target, dataObject) {
    var displayValue = dataObject.label.replace('\n','');

    var existingSpan = false;

    existingSpan = document.getElementById("span_" + displayValue);

    if (!existingSpan) {
        var span = $j("<span>").text(displayValue); //Create a new span tag to display the selected value
        span.attr({ id: "span_" + dataObject.value });
        var hiddenFld = $j("<input>").attr({ type: "hidden" }).val(dataObject.value); //Create a div object to store the code value
        hiddenFld.addClass(target + "IdField").css("visibility", "hidden").css("height", 0).attr({ id: target, name: target }); //Format the div
        var a = $j("<a>").addClass(target + "remove").attr({
            href: "javascript:",
            title: "Remove " + displayValue
        }).text("x").appendTo(span); //Define the "x" to remove the span

        hiddenFld.appendTo(span); //Append the div to the span
        span.insertBefore("#" + target + "_display"); //Insert span before the concealed text box
        $j("#" + target).attr({ value: dataObject.value }); //Store the ID value related to the selected item
        $j("#" + target + "_display").val("").css("top", 2); //Store the ID value related to the selected item
        //$j("#" + target + "_display").flushCache(); //Flush the cache for the autocomplete control
    } else {
        alert("This item has already been selected");
    }
}

The setAutocompleteState method:-

function setAutocompleteState(targetName, IsMultiSelect, HasSelections) {
    if (!IsMultiSelect && HasSelections) {
        $j("#" + targetName).autocomplete("option", "disabled", true);
    } else {
        $j("#" + targetName).autocomplete("option", "disabled", false);
    }
}

The isMultiSelect and HasSelections define whether or not the autocomplete should be enabled, and the targetName is simply the ID of the textbox that has been "autocompleted"

や三分注定 2024-11-12 06:56:00

与自动完成控件一起使用的样式

.acarea { padding:3px 3px 0; margin:0 auto; background-color:#fff; cursor:text; }
.acarea div {border:1px solid #aaa; }
.acarea input {border:0px; display:inline;}
.acarea span { display:block; width:auto; margin:0 3px 3px 0; padding:3px 20px 4px 8px; position:relative; float:left; text-indent:0; background-color:#eee; border:1px solid #333; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; color:#333; font:normal 11px Verdana, Sans-serif; }
.acarea span a { position:absolute; right:8px; top:2px; color:#666; font:bold 12px Verdana, Sans-serif; text-decoration:none; }
.acarea span a:hover { color:#ff0000; }
.ui-menu .ui-menu-item { white-space:nowrap; padding:0 10px 0 0; }

自动完成控件的库函数

//Function to write the entries into the text box
function displayItem(target, dataObject) {
    var displayValue = dataObject.label.replace('\n','');

    var existingSpan = false;

    existingSpan = document.getElementById("span_" + displayValue);

    if (!existingSpan) {
        var span = $j("<span>").text(displayValue); //Create a new span tag to display the selected value
        span.attr({ id: "span_" + dataObject.value });
        var hiddenFld = $j("<input>").attr({ type: "hidden" }).val(dataObject.value); //Create a div object to store the code value
        hiddenFld.addClass(target + "IdField").css("visibility", "hidden").css("height", 0).attr({ id: target, name: target }); //Format the div
        var a = $j("<a>").addClass(target + "remove").attr({
            href: "javascript:",
            title: "Remove " + displayValue
        }).text("x").appendTo(span); //Define the "x" to remove the span

        hiddenFld.appendTo(span); //Append the div to the span
        span.insertBefore("#" + target + "_display"); //Insert span before the concealed text box
        $j("#" + target).attr({ value: dataObject.value }); //Store the ID value related to the selected item
        $j("#" + target + "_display").val("").css("top", 2); //Store the ID value related to the selected item
        //$j("#" + target + "_display").flushCache(); //Flush the cache for the autocomplete control
    } else {
        alert("This item has already been selected");
    }
}

//function to load the existing data as entries
//targetName is the id of the control being rendered
//existingEntries is an array of objects that contain a label and value property (at least!!)
function loadItems(targetName, existingEntries){
    for (i=0;i<existingEntries.length;i++) {
        displayItem(targetName, existingEntries[i]);
    } //End of for loop
} //End of function

function setAutocompleteState(targetName, IsMultiSelect, HasSelections) {
    if (!IsMultiSelect && HasSelections) {
        $j("#" + targetName).autocomplete("option", "disabled", true);
    } else {
        $j("#" + targetName).autocomplete("option", "disabled", false);
    }
}

由 MVC 扩展方法呈现

<script language="javascript">
var Autocomp1_existingEntries = null;
var Autocomp1_IsMultiSelect = false;
var Autocomp1_HasSelections = false;
</script>

<div class="acarea" id="Autocomp1_acarea"><div class="ui-helper-clearfix"><input id="Autocomp1_display" type="text" /></div></div>

<script type="text/javascript" language="javascript">
$j(document).ready(function () {
$j("#Autocomp1_display").autocomplete({
source: function(request, response){
    $j.ajaxSetup({cache: false});
    $j.ajax({
    url: "AutoComplete.asmx/GetUniversities",
    type: "GET",
    data: request,
    dataType: "json",
    success: function (data) {
            request.term="";
            response(data);
        }
    });
},
cache: false,
select: function(e, ui){
    displayItem("Autocomp1", ui.item);
    Autocomp1_HasSelections = true;
    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
    $j('#Autocomp1').change();
    return false;
},
focus: function(event, ui){
    if (ui.item.label){
        $j(this).val(ui.item.label);
    } else {
        $j(this).val(ui.item.value);
    }
    return false;
}});
})

if (Autocomp1_existingEntries != null){
    loadItems("Autocomp1", Autocomp1_existingEntries);
    Autocomp1_HasSelections = true;
    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
}

$j("#Autocomp1_acarea").click(function() {
    $j("#Autocomp1_display").focus();
});

$j(".Autocomp1remove", document.getElementById("Autocomp1_acarea")).live("click", function() {
    var spanDiv = $j(this).parent().parent();
    $j(this).parent().remove();
    Autocomp1_HasSelections = false;
    var Autocomp1_nodeCounter = 0;

    for (Autocomp1_nodeCounter = 0;Autocomp1_nodeCounter < spanDiv[0].childNodes.length; Autocomp1_nodeCounter++){
        if (spanDiv[0].childNodes[Autocomp1_nodeCounter].nodeName.toLowerCase()=="span"){
            Autocomp1_HasSelections = true;     break;
        }
    }

    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
    if ($j("#Autocomp1_acarea span").length === 0) {
        $j("#Autocomp1_display").css("top", 0).val("");
    }
    $j('#Autocomp1').change();
});

的代码 这是我在呈现自动完成控件并让它在 div 内存储所选值时使用的完整代码。请随意按摩它,让它为您发挥作用。

Styles used with the autocomplete control

.acarea { padding:3px 3px 0; margin:0 auto; background-color:#fff; cursor:text; }
.acarea div {border:1px solid #aaa; }
.acarea input {border:0px; display:inline;}
.acarea span { display:block; width:auto; margin:0 3px 3px 0; padding:3px 20px 4px 8px; position:relative; float:left; text-indent:0; background-color:#eee; border:1px solid #333; -moz-border-radius:7px; -webkit-border-radius:7px; border-radius:7px; color:#333; font:normal 11px Verdana, Sans-serif; }
.acarea span a { position:absolute; right:8px; top:2px; color:#666; font:bold 12px Verdana, Sans-serif; text-decoration:none; }
.acarea span a:hover { color:#ff0000; }
.ui-menu .ui-menu-item { white-space:nowrap; padding:0 10px 0 0; }

Library functions for the autocomplete control

//Function to write the entries into the text box
function displayItem(target, dataObject) {
    var displayValue = dataObject.label.replace('\n','');

    var existingSpan = false;

    existingSpan = document.getElementById("span_" + displayValue);

    if (!existingSpan) {
        var span = $j("<span>").text(displayValue); //Create a new span tag to display the selected value
        span.attr({ id: "span_" + dataObject.value });
        var hiddenFld = $j("<input>").attr({ type: "hidden" }).val(dataObject.value); //Create a div object to store the code value
        hiddenFld.addClass(target + "IdField").css("visibility", "hidden").css("height", 0).attr({ id: target, name: target }); //Format the div
        var a = $j("<a>").addClass(target + "remove").attr({
            href: "javascript:",
            title: "Remove " + displayValue
        }).text("x").appendTo(span); //Define the "x" to remove the span

        hiddenFld.appendTo(span); //Append the div to the span
        span.insertBefore("#" + target + "_display"); //Insert span before the concealed text box
        $j("#" + target).attr({ value: dataObject.value }); //Store the ID value related to the selected item
        $j("#" + target + "_display").val("").css("top", 2); //Store the ID value related to the selected item
        //$j("#" + target + "_display").flushCache(); //Flush the cache for the autocomplete control
    } else {
        alert("This item has already been selected");
    }
}

//function to load the existing data as entries
//targetName is the id of the control being rendered
//existingEntries is an array of objects that contain a label and value property (at least!!)
function loadItems(targetName, existingEntries){
    for (i=0;i<existingEntries.length;i++) {
        displayItem(targetName, existingEntries[i]);
    } //End of for loop
} //End of function

function setAutocompleteState(targetName, IsMultiSelect, HasSelections) {
    if (!IsMultiSelect && HasSelections) {
        $j("#" + targetName).autocomplete("option", "disabled", true);
    } else {
        $j("#" + targetName).autocomplete("option", "disabled", false);
    }
}

Code that is rendered by the MVC extension method

<script language="javascript">
var Autocomp1_existingEntries = null;
var Autocomp1_IsMultiSelect = false;
var Autocomp1_HasSelections = false;
</script>

<div class="acarea" id="Autocomp1_acarea"><div class="ui-helper-clearfix"><input id="Autocomp1_display" type="text" /></div></div>

<script type="text/javascript" language="javascript">
$j(document).ready(function () {
$j("#Autocomp1_display").autocomplete({
source: function(request, response){
    $j.ajaxSetup({cache: false});
    $j.ajax({
    url: "AutoComplete.asmx/GetUniversities",
    type: "GET",
    data: request,
    dataType: "json",
    success: function (data) {
            request.term="";
            response(data);
        }
    });
},
cache: false,
select: function(e, ui){
    displayItem("Autocomp1", ui.item);
    Autocomp1_HasSelections = true;
    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
    $j('#Autocomp1').change();
    return false;
},
focus: function(event, ui){
    if (ui.item.label){
        $j(this).val(ui.item.label);
    } else {
        $j(this).val(ui.item.value);
    }
    return false;
}});
})

if (Autocomp1_existingEntries != null){
    loadItems("Autocomp1", Autocomp1_existingEntries);
    Autocomp1_HasSelections = true;
    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
}

$j("#Autocomp1_acarea").click(function() {
    $j("#Autocomp1_display").focus();
});

$j(".Autocomp1remove", document.getElementById("Autocomp1_acarea")).live("click", function() {
    var spanDiv = $j(this).parent().parent();
    $j(this).parent().remove();
    Autocomp1_HasSelections = false;
    var Autocomp1_nodeCounter = 0;

    for (Autocomp1_nodeCounter = 0;Autocomp1_nodeCounter < spanDiv[0].childNodes.length; Autocomp1_nodeCounter++){
        if (spanDiv[0].childNodes[Autocomp1_nodeCounter].nodeName.toLowerCase()=="span"){
            Autocomp1_HasSelections = true;     break;
        }
    }

    setAutocompleteState("Autocomp1_display", Autocomp1_IsMultiSelect, Autocomp1_HasSelections);
    if ($j("#Autocomp1_acarea span").length === 0) {
        $j("#Autocomp1_display").css("top", 0).val("");
    }
    $j('#Autocomp1').change();
});

This is the entirity of the code that I use in rendering the autocomplete control and getting it to store the selected values inside a div. Feel free to massage it to get it to work for you.

过气美图社 2024-11-12 06:56:00

我编写了一个 Asp.Net WebControl 来包装 JQuery UI 自动完成小部件。
WebControl 提供了一个属性:OnClientSelection,您可以将其设置为 javascript 函数名称。
在幕后,它所做的正是您指定“选择”操作所做的。
我编写了有关如何使用该控件的文档。

您可以在以下位置找到它:

http://autocompletedotnet.codeplex.com/

希望它能有所帮助

I wrote an Asp.Net WebControl wrapping the JQuery UI autocomplete widget.
The WebControl provides a property: OnClientSelection that you can set to a javascript function name.
Under the hood what it does is exactly what you did specifying the 'select' action.
I wrote documentation about how to use the control.

You can find it at:

http://autocompletedotnet.codeplex.com/

Hope it can help

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文