Reputation: 2079
I am using JQuery autocomplete in one of our web pages which gets source data from a url and wokring ok. {
$(function () {
$("#name-list").autocomplete({
source: function (request, response) {
$.ajax({
url: "/MemberType/FindMemberTypes", type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.DisplayText, value: item.description, id: item.id }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
}
});
});
}
The url "membertype/findmemberTypes" searches memberType table and returns list of member types in Json format.
The problem I have here is every time the use keys in some character in the textbox, ONE request is made to the server,the table is scanned and the data is returned to the caller. I want to change the behavior in such a way that there is only one trip to the server when user really wants to search for the text.
Is it possible to trigger auto-complete only after user presses "Enter key" in the textbox?
Upvotes: 1
Views: 853
Reputation: 2079
Thanks Guys for your answers and time.
After mocking around for a while, I found a solution to this which just suits my requirement.
I just added some code to disable the autocomplete altogether and enable it only when user presses enter. When user tries to enter a different text by pressing backspace or delete keys, feature is disabled back again.
<input type="text" id="name-list" /> (Press enter for options)
<script type="text/javascript" language="javascript">
$(function () {
$("#name-list").autocomplete({
source: function (request, response) {
$.ajax({
url: "/MemberType/FindMemberTypes", type: "POST", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
success: function (data) {
response($.map(data, function (item) {
return { label: item.description, value: item.description, id: item.id }
}))
}
})
},
select: function (event, ui) {
alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
: "Nothing selected, input was " + this.value);
}
}).keypress(function (e) {
if (e.keyCode === 13) {
$("#name-list").autocomplete("enable");
$("#name-list").autocomplete("search", $("name-list").val());
}
else if ((e.keyCode == 8) || (this.value == "") || (e.keyCode == 46))
{
$("#name-list").autocomplete("disable");
}
}); ;
$("#name-list").autocomplete("disable");
});
</script>
Upvotes: 2
Reputation: 126
jQuery UI autocomplete wont search when the enter key is pressed, the enter key is only used when the menu is displayed after searching
You could look at setting the delay and minLength options to reduce the amount of requests made.
Or you could look at another autocomplete plugin that fires when the enter key is pressed.
Upvotes: 1