I am using jQuery autocomplete with a textbox under asp.net mvc 2, and everything works fine. I type in a search and it returns a list of results. But if I type some characters then backspace and erase all the text out of the text box I want a default list of items to appear. Unfortunatley the ajax call to my controller does not get fired after backspacing and removing all the text.
One thing I need to mention I am using the autocomplete in a slightly different way. I am using the autocomplete functionality to act like a filtering mechanism. When the user types into the text box a ajax call is made and the results are injected into a div tag. I do not want the standard drop down to appear under the textbox, I just want to use the functionality that autocomplete provides to dynamically display a list of items in a page as i type a filter string.
I am doing this because the list of results are in the hundreds and having the ability to type a few characters an return a filtered result makes it much faster to find a item in the list.
To get around this i have tried hooking into the textbox onchange/onkeypress/onkeyup events etc and checking if there is any text in the text box and if there is none display the default list. But again it does not want to work for me. It's as if the textbox events do not fire when the text is deleted from the textbox.
I would like to find a way so that when the text in the textbox is deleted a default search is performed automatically.
Here is my html ...
<% using (this.Html.BeginForm("Filter", "Guilds"))
{%>
Filter:
<input type="text" name="SearchFilterText" value="" id="filterTextBox" onkeyup="onfilterchange();" />
<%
}%>
<script type="text/javascript">
$(function () {
$("#filterTextBox").autocomplete({
source: [""],
search: function (event, ui) {
populatelist();
return true;
},
minLength: 1,
delay: 300
});
});
</script>
<div id="success">
<% Html.RenderPartial("GuildList", this.Model); %>
</div>
<div id="error">
</div>
here is my script in the head section....
function populatelist() { var url = "/FilteredGuilds///"; $.ajax({ url: url + $("#filterTextBox").val(), dataType: "html", success: function(response, status, xhr) { $('#success').html(response); $("#error").html(""); }, error: function(response, status, xhr) { if (status == "error") { $("#success").html(""); var msg = "Sorry but there was an error: "; $("#error").html(msg + xhr.status + " " + xhr.statusText); } } }); } function onfilterchange(){ if($("#filterTextBox").val() == null | $("#filterTextBox").val() ==""){ populatelist(); } }
And here is my controller action....
[HttpGet] public PartialViewResult Filter(string realm, DateTime date, string filter) { var guildNames = this._repository.GetGuildNames(date, realm); if (string.IsNullOrEmpty(filter)) return PartialView("GuildList", guildNames); return PartialView("GuildList", guildNames.Where(x => x.Name.ToLower().Trim().Contains(filter.ToLower().Trim())).ToList()); }