I have a bootstrap modal dialog on which I have a textbox that I want to leverage the functionality of jQuery UI Autocomplete widget. However the autocomplete widget isn't being fired at all. I know this as I placed a breakpoint on the action on my controller that should return the Json to be rendered by the autocomplete textbox. The action is never hit
Out of curiosity that I was doing something wrong, I copy pasted the textbox onto a View and to my dismay, the breakpoint on my action in the controller is hit. I have narrowed this down to the fact that may be the textbox is never wired to use the autocomplete feature once the DOM has loaded. Here is the textbox on my modal
<input type="text" name="someName" id="autocomplete" data-autocomplete-url="@Url.Action("Autocomplete", "warehouses")" />
Here is the action method that returns the Json
public ActionResult Autocomplete(string term) { string[] names = { "Auma", "Dennis", "Derrick", "Dylan", "Mary", "Martha", "Marie", "Milly", "Abel", "Maria", "Bergkamp", "Arsene", "Alex", "Mwaura", "Achieng" }; var filtered = names.Where(a => a.IndexOf(term, StringComparison.OrdinalIgnoreCase) >= 0); return Json(filtered, JsonRequestBehavior.AllowGet); }
And here is how I wire up the textbox to use the autocomplete widget
$(document).ready(function () { $('#autocomplete').autocomplete({ source: $(this).data('autocomplete-url'), data: {term: $(this).val() } });
});
I have seen similar questions asked but none of them was due to the action not being hit.
1 Answers
Answers 1
As per the documentation for Bootstrap 3, they expose a set of events that you can hook into with most of their JS features.
In this case the events are: show, shown, hide, hidden and loaded
The following code will initialize your autocomplete input field after the modal has been shown. (replace myModal with the id of the modal you are going to show)
$(document).ready(function () { $('#myModal').on('shown.bs.modal', function (e) { $("#autocomplete').autocomplete('destroy'); //remove autocompete to reattach $('#autocomplete').autocomplete({ source: $(this).data('autocomplete-url'), data: {term: $(this).val() } }); }); });
If you are fetching a partial that contains the input field and appending it to the modal during the toggle, it will be better to do this initialization in the callback from that ajax request.
0 comments:
Post a Comment