I'd specifically like to prevent the interaction when I push ENTER to prevent jQueryUI Autocomplete from selecting the currently focused item and closing the menu.
I'm referring to the following documentation: http://api.jqueryui.com/autocomplete/#event-change
UPDATE:
The principle is the same. Just change the setTimeout
function to submit your form instead (as demonstrated here: http://jsfiddle.net/X8Ghc/8/)
UPDATE:
You are correct, $(this)
was supposed to refer to the ui-menu
(and obviously didn't). The new fiddle, http://jsfiddle.net/X8Ghc/7/, works reasonably well.
$(document).ready(function() {
$("#autocomplete").autocomplete({
"open": function(e, ui) {
//using the 'open' event to capture the originally typed text
var self = $(this),
val = self.val();
//saving original search term in 'data'.
self.data('searchTerm', val);
},
"select": function(e, ui) {
var self = $(this),
keyPressed = e.keyCode,
keyWasEnter = e.keyCode === 13,
useSelection = true,
val = self.data('searchTerm');
if (keyPressed) {
if (keyWasEnter) {
useSelection = false;
e.preventDefault();
window.setTimeout(function() {
//since there is apparently no way to prevent this
//contemptible menu from closing, re-open the menu
//using the original search term after this handler
//finishes executing (using 'setTimeout' with a delay
//of 0 milliseconds).
self.val(val);
self.autocomplete('search', val);
}, 0);
}
}
return useSelection;
},
"source": ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
});
});
Original:
This works in a fiddle:
$(document).ready(function() {
$("#autocomplete").autocomplete({
"select": function(e, ui) {
var keyPressed = e.keyCode,
keyWasEnter = e.keyCode === 13,
useSelection = true;
console.log(e);
if (keyPressed) {
if (keyWasEnter) {
useSelection = false;
$(this).open(e, ui);
}
}
return useSelection;
},
"source": ["c++", "java", "php", "coldfusion", "javascript", "asp", "ruby"]
});
});