Jquery ui 自动完成用 ID 填充隐藏字段
我正在尝试让自动完成插件在一个文本框中填充大学名称,在另一个文本框中填充大学代码。下面的代码返回结果并填充大学名称文本框,但我不知道如何填充另一个输入。
我尝试按照此示例进行操作,但是跨越问题甚至调用网络方法。一件奇怪的事情是,似乎 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我能够通过添加选择事件来使其工作。在我之前的测试中,我把它放在那里,但在错误的位置(最初嵌套在成功事件中)。还必须在成功事件中添加设置值的三行:item.Descr、 Descr: item.Descr 和 UnivCode: item.UnivCode。我不太明白它们引用了什么或它们在做什么,因为输入的实际设置是在 select 事件中完成的,我在其中指定了输入的实际 id ($('#university').val(ui .item.Descr);),但这是让代码正常工作所必需的。
这是工作中的 jquery,没有对 html 或 .net 代码进行任何其他更改。
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.
我在使用 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 方法将所选项目的显示值写入此文本框,并将所选值放入隐藏范围中。
select 事件使用如下的 displayItem 方法
setAutocompleteState 方法: -
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.
The select event makes use of the displayItem method as below
The setAutocompleteState method:-
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"
与自动完成控件一起使用的样式
自动完成控件的库函数
由 MVC 扩展方法呈现
的代码 这是我在呈现自动完成控件并让它在 div 内存储所选值时使用的完整代码。请随意按摩它,让它为您发挥作用。
Styles used with the autocomplete control
Library functions for the autocomplete control
Code that is rendered by the MVC extension method
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.
我编写了一个 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