【发布时间】:2009-12-30 16:20:33
【问题描述】:
有autocomplete,但它不会强制选择项目。我需要这样的东西,但它必须在你“提交”之前强制选择一个项目。
它存在吗?
【问题讨论】:
-
你不能在'onChange'下拉列表中设置一个“监听器”吗?如果它发生了变化,则表示已选择了某些内容,因此您可以启用提交按钮。
标签: jquery autocomplete
有autocomplete,但它不会强制选择项目。我需要这样的东西,但它必须在你“提交”之前强制选择一个项目。
它存在吗?
【问题讨论】:
标签: jquery autocomplete
你可以使用"change" event 的自动完成
var availableTags = [
"ActionScript",
"AppleScript"
];
$("#tags").autocomplete({
source: availableTags,
change: function (event, ui) {
if(!ui.item){
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$("#tags").val("");
}
}
});
【讨论】:
这是我使用 .blur 的解决方案(此外,我使用名称|ID 对)
jQuery("#username").autocomplete(
"/yii_app/stock/suggestUser",
{
'mustMatch':true,
'multiple':false,
'formatItem':function(result, i, num, term) {
return '<small>'+result[1]+'</small> '+ result[0];
}
}
).result(
function(event,item) {
$("#user_id").val(item[1]);
}
).blur(
function() {
$("#user_id").val('');
$(this).search();
}
);
user_id 是隐藏输入字段,username 是文本输入字段 ajax 结果使用以下格式: user1name|user1id\n user2name|user2id\n
【讨论】:
使用选项:
mustMatch:true,
这在 Bassistance 自动完成插件中可用。我不知道它是 jQuery 自动完成还是 Bassistance 的自动完成的一部分,但它可以工作!
【讨论】:
这是我目前使用jQuery UI的autocomplete的解决方案:
$('#some-input').autocomplete({
source: 'some-url',
autoFocus: true,
minLength: 2,
select: function(event, ui) {
//remember the selected item
$('#some-input')
.data('selected-item', ui.item.label);
}
}).blur(function() {
var value = $('#some-input').val();
//check if the input's value matches the selected item
if(value != $('#some-input').data('selected-item')) {
//they don't, the user must have typed something else
$('#some-input')
.val('') //clear the input's text
.data('selected-item', ''); //clear the selected item
}
});
每次触发模糊事件时,都会检查输入的值是否先前已被选取。如果它没有被选中(你知道,因为 select 事件从未触发),'selected-item' 变量将与输入的值不匹配。然后你可以做任何你想做的事情(我清除了输入,但你可以尝试别的)。
【讨论】:
将它与validation 插件结合使用。只需为验证插件设置字段required。
【讨论】:
你也可以使用内置的提交事件
$('Autocomplete').autocomplete({
select: function(event, ui) {
$('submit').show();
}
});
【讨论】: