使用jQuery-UI自动完成选择选项时设置多个输入的值
Set the Values of Multiple Inputs When Selecting an Option using jQuery-UI Autocomplete
大家好,我是java脚本新手。所以我希望你能帮助我。当用户将数据设置为城市字段时,我想在国家字段中自动设置数据。我有一个xml文件:
<ROWSET>
<ROW>
<city></city>
<country></country>
</ROW>
</ROWSET>
在html文档中我有两个输入字段
<input id="id_city">
<input id="country">
这是我的js代码:
$.ajax({
url: "/media/xml/country.xml", //your url
type: "GET", //may not need this-fiddle did-default is GET
dataType: "xml",
success: function(xmlResponse) {
var data = $("ROW", xmlResponse).map(function() {
return {
value: $("city", this).text() + ", " + ($.trim($("country", this).text()) || "(unknown country)")
};
}).get();
$("#id_city").autocomplete({
source: function(req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function(item) {
return matcher.test(item.value);
}));
},
minLength: 2,
select: function(event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.value + ", cityId: " + ui.item.id : "Nothing selected, input was " + this.value);
}
});
}
});
我不知道如何将数据自动设置为国家字段谢谢。
好了。我已经改变了data
的定义,现在它有三个属性:
-
label
与您原来的value
相同。 -
city
,因此您可以将其放入#city
输入。 -
country
,所以你可以把它放在你的#country
输入。
这意味着你可以使用ui.item.city
和ui.item.country
在自动完成的选择属性。
因为现在有三个属性,你需要自定义自动完成,并告诉它使用label
的选项,这是_renderItem
部分所做的。
$.ajax({
url: "/media/xml/country.xml",
type: "GET",
dataType: "xml",
success: function (xmlResponse) {
var data = $("ROW", xmlResponse).map(function () {
return {
label: $("city", this).text() + ", " + ($.trim($("country", this).text()) || "(unknown country)"),
city: $.trim($("city", this).text()),
country: $.trim($("country", this).text())
};
}).get();
$("#id_city").autocomplete({
source: function (req, response) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function (item) {
return matcher.test(item.city);
}));
},
minLength: 2,
select: function (event, ui) {
$("p#result").html(ui.item ? "Selected: " + ui.item.label + ", cityId: " + ui.item.city : "Nothing selected, input was " + this.value);
$("#id_city").val(ui.item.city);
$("#country").val(ui.item.country);
return false;
},
_renderItem: function (ul, item) {
return $("<li></li>")
.data("value", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
});
}
});
我还创建了一个"工作"的Fiddle(因为你的代码是使用ajax XML源,我已经硬编码在一个变量的响应,并在error
属性中生成自动完成,因为ajax请求总是从jsfiddle.net失败)。
相关文章:
- 如果值为空,如何设置输入的默认值?jQuery
- 如何设置输入文本框jquery的值
- jQuery - 添加删除类 - 设置输入值
- 可以设置输入类型=文件的文本框的高度
- 在jquery中,从同一对象的属性设置输入字段和标签的正确方法是什么
- 设置输入类型月份的值
- 整数 + 2x 单选按钮设置输入 --> 输出
- jQuery timepicker:如何动态设置输入字段的minTime
- 设置输入类型=日期
- IE 9 jQuery未设置输入值
- React设置输入's值
- 使用jquery设置输入数组值
- 如何使用javascscript设置输入值
- 使用 javascript 设置输入标签的值
- 根据角度中的另一个字段设置输入字段的默认值
- 如何设置输入元素的值
- 如何在哈希中设置输入值
- 我如何在 jQuery 中以编程方式设置输入文本框的值
- Javascript在加载后设置输入值
- 无法使用 Javascript 设置输入的值