我正在使用 jquery 自动完成组合框 一切都很好。但我也想通过 JavaScript 设置特定值,如
$("#value").val("somevalue")
并将其设置为选择元素,但自动完成功能不会更改输入元素。
当然,我可以直接选择这个输入并设置值,但是还有其他方法吗?我尝试将绑定设置为
this.element
,就像this.element.bind("change", function(){alert(1)})
一样,但没有效果。我不知道为什么。
编辑
我找到了解决这种情况的方法。但我不喜欢它。我已将以下代码添加到 ui.combobox 的 _create 函数中
this.element.bind("change", function() {
input.val( $(select).find("option:selected").text());
});
当我需要更改值时,我可以使用
$("#selector").val("specificvalue").trigger("change");
我采用了一种快速但肮脏的方法来设置该值。 但是,您确实需要知道要在下拉列表中显示的项目的值和文本。
var myValue = foo; // value that you want selected
var myText = bar; // text that you want to display
// You first need to set the value of the (hidden) select list
$('#myCombo').val(myValue);
// ...then you need to set the display text of the actual autocomplete box.
$('#myCombo').siblings('.ui-combobox').find('.ui-autocomplete-input').val(myText);
@andyb, 我想重写:
autocomplete: function (value) {
this.element.val(value);
var selected = this.element.children(":selected"),
value = selected.val() ? selected.text() : "";
this.input.val(value);
}
我真的很喜欢 andyb 所做的事情,但我需要它在事件处理方面做更多的事情,以便能够处理触发更改事件,因为“选定”在按 Enter 或失去输入焦点时不会处理(按 Tab 键)或鼠标点击)。
因此,使用 andyb 所做的基础以及最新版本的 jQuery 自动完成脚本,我创建了以下解决方案:DEMO
如何使用Change方法:
$("#combobox").combobox({
selected: function (event, ui) {
$("#output").text("Selected Event >>> " + $("#combobox").val());
}
})
.change(function (e) {
$("#output").text("Change Event >>> " + $("#combobox").val());
});
希望这可以帮助其他需要额外更改事件功能的人来弥补“选定”留下的空白。
截至 2025 年,以下方法似乎有效:
$("#selector").val("specificvalue").data("autocomplete-selection", "specificvalue");
$(".document").ready(function(){
$("select option:eq(1)").val("someNewVal");
$("select option:eq(1)").text("Another Val");
$("select option:eq(1)").attr('selected', 'selected');
});
这里是一个工作示例和jquery,我假设您想要更改选择的值,更改其文本外观并在页面加载时选择它?
#尝试2:
这是另一个小提琴:http://jsfiddle.net/HafLW/1/,你的意思是你选择一个选项,然后你想将该值附加到输入区域的自动完成中?
$(".document").ready(function(){
someString = "this,that";
$("input").autocomplete({source: someString.split(",")});
$("select").change(function(){
alert($(this).val()+" appended");
someString = someString+","+$(this).val();
$("input").autocomplete({source: someString.split(",")});
});
});