我有一个 jQuery UI 对话框,其中包含一个填充有各种标签的 jQuery UI 自动完成输入框。对话框本身的按钮 Pane 中有两个按钮:“选择”和“取消”。但是,我想根据用户当前在输入框的文本字段中的内容来启用和禁用“选择”按钮。换句话说,自动完成功能使用的可用标签列表包含用户可以选择的所有有效选项。因此,如果他们从自动完成中选择这些标签之一,“选择”按钮将被启用,允许他们单击它。此外,如果他们只是输入正确的标签,而没有从自动完成的下拉框中实际选择标签之一,我仍然希望启用此“选择”按钮。
起初,我认为每次输入字段与可用标签列表发生变化时,我都会交叉引用输入框中当前的文本,以查看是否应该启用“选择”按钮,但到目前为止,它似乎不起作用。关于我如何实现这一目标有什么建议吗?这是我迄今为止尝试过的:
$("#dialog").dialog({
autoOpen: false,
buttons: {
Select: function() {
// Carry out some proceedure knowing they've selected a valid label.
},
Cancel: function() {
// Cancels the selection and closes the dialog box.
}
},
closeOnEscape: false,
create: function(event, ui) {
var labels = ["Bird", "Boar", "Dog", "Dragon", "Ox", "Tiger"];
$("#input").autocomplete({
delay: 0,
source: labels
});
$("#input").change(function() {
$(".ui-dialog-buttonpane button:contains('Select')").button("disable");
labels.each(function() {
if($("#input").text() == $(this)) {
$(".ui-dialog-buttonpane button:contains('Select')").button("enable");
return;
}
});
});
},
draggable: false,
modal: true,
resizable: false,
title: "Select Dialog",
width: 460
});
最佳答案
你已经很接近了,使用 $.inArray
怎么样?切换按钮?此外,您需要使用 $(this).val()
或 this.value
来计算 input
元素的值。
$("#dialog").dialog({
autoOpen: false,
buttons: {
Select: function() {
// Carry out some proceedure knowing they've selected a valid label.
},
Cancel: function() {
// Cancels the selection and closes the dialog box.
}
},
closeOnEscape: false,
create: function(event, ui) {
var labels = ["Bird", "Boar", "Dog", "Dragon", "Ox", "Tiger"];
$("#input").autocomplete({
delay: 0,
source: labels
});
$("#input").change(function() {
var enabled = $.inArray(this.value, labels) >= 0 ? "enable" : "disable";
$(".ui-dialog-buttonpane button:contains('Select')").button(enabled);
});
},
draggable: false,
modal: true,
resizable: false,
title: "Select Dialog",
width: 460
});
示例: http://jsfiddle.net/kcrBB/
<小时/>根据评论,这是一个使用 keyup
而不是更改的示例:
$("#dialog").dialog({
open: function () {
$(".ui-dialog-buttonpane button:contains('Select')").button("disable");
},
buttons: {
Select: function() {
// Carry out some proceedure knowing they've selected a valid label.
},
Cancel: function() {
// Cancels the selection and closes the dialog box.
}
},
closeOnEscape: false,
create: function(event, ui) {
var labels = ["Bird", "Boar", "Dog", "Dragon", "Ox", "Tiger"];
$("#input").autocomplete({
delay: 0,
source: labels,
select: function () {
$(".ui-dialog-buttonpane button:contains('Select')").button("enable");
}
});
$("#input").keyup(function() {
var enabled = $.inArray(this.value, labels) >= 0 ? "enable" : "disable";
$(".ui-dialog-buttonpane button:contains('Select')").button(enabled);
});
},
draggable: false,
modal: true,
resizable: false,
title: "Select Dialog",
width: 460
});
关于jquery - 选择 jQuery UI 自动完成中的有效标签时启用 jQuery UI 对话框按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8583607/