我希望为用户提供添加自己的变体的可能性,而不仅仅是建议的变体.但是当我在字段中键入内容并单击ENTER时,我的表单会提交.
然后我尝试捕获我的字段的keydown事件,但在这种情况下,我没有可能从使用箭头的建议中选择变体并输入键,因为ui参数未定义.
$('#field_id').on('keydown',function(event) {
if (event.keyCode == $.ui.keyCode.ENTER
|| event.keyCode == $.ui.keyCode.NUMPAD_ENTER)
{
$('#field_id').trigger('autocompleteselect');
}
});
$('#field_id').autocomplete({
source: [{"id":"20","value":"This is not mandatory decline reason"},{"id":"21","value":"You are have to be rejected"}]
minLength: 0
}).on('autocompleteselect',function(event,ui) {
// if I click on suggestion using mouse - everything is ok
// but not for ENTER-key choosing
// I want something like that:
if (ui.item) {
id = ui.item.id;
value = ui.item.value;
} else {
id = 'my_new_item';
value = $(this).val();
}
return false;
});
最佳答案
如果您想阻止表单在输入时提交,您可以使用preventDefault:
原文链接:https://www.f2er.com/jquery/428169.html$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
对于自动完成,请注意,当按下回车键时触发’autocompleteselect’事件将在用户点击建议项目时触发’autocompleteselect’处理程序两次.要避免这种情况和缺少的ui参数,请尝试使用响应回调并将autofocus设置为true,将用户输入添加为建议项目.
$('#field_id').autocomplete({
source: [{
"id": "20","value": "This is not mandatory decline reason"
},{
"id": "21","value": "You are have to be rejected"
}],minLength: 0,autoFocus: true,response: function (event,ui) {
if (ui.content.length == 0) {
ui.content.push({
label: "New Search value: " + $(this).val(),value: $(this).val(),id: 0
});
}
}
}).on('autocompleteselect',function (event,ui) {
id = ui.item.id;
value = ui.item.value;
return false;
});
这是上面的一个jsfiddle例子.
希望这可以帮助.