Reputation: 1659
I am using a JQuery(1.9.1) autocomplete dropdown. I want the user to type a system name in the dropdown and have the dropdown be updated as the user adds characters. I also want there to be a default value of "Other" always present on the top of the dropdown regardless of what characters the user enters. Here is a screenshot of what it should look like:
Here is my ajax call for that :
$.ajax({
type: 'POST'
, url: '/test/get_BackendSystems'
, dataType: 'json'
, success: function (response) {
if (response.success) {
backend_systems = [];
$.each(response.backend_systems, function (id,system_object) {
backend_systems.push(system_object["system"]);
});
}
$("#BackEnd").autocomplete({
source: backend_systems,
open: function(){
$(this).data("autocomplete").menu.element.addClass("backend_dropdown");
$('.backend_dropdown').prepend('<li class="ui-menu-item" role="menuitem"><a class="ui-corner-all ui-add-new" tabindex="-1">Other</a></li>');
$('.backend_dropdown').width(432);
}
});
}
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Here is the corresponding html:
<div class='referral wrapper'>
<input list="POS_options" name="data[Account][backend_system]" type="text" class="required" placeholder="Back-End System" maxlength="150" id="BackEnd">
</div>
Thie drop down looks the way I want except whenever I click "Other" from the dropdown I get this error in the chrome console and "Other" does not populate the input text box: "Uncaught TypeError: Cannot read property 'data' of undefined". Clicking the other options works fine.
Anyone know what I am doing wrong or have an alternative way to get this type of drop down? I suspect the issue is something to do with the interaction of autocomplete with prepend, since all the options besides "Other" work fine. If there are other ways of doing this besides jquery autocomplete I would be open to trying that as well.
Upvotes: 0
Views: 1133
Reputation: 3618
Have you seen the SO answer here? Always show a specific choice in jQuery Autocomplete even if it doesn't match input
The formatting is incorrect in the answer (Im still working through it to determine how the HTML format should appear) but it seems very similar to what you (and I!) are trying to accomplish.
Upvotes: 0
Reputation: 3614
I would try to prepend the 'Other' option where you define array, like this:
$.ajax({
type: 'POST'
, url: '/test/get_BackendSystems'
, dataType: 'json'
, success: function (response) {
if (response.success) {
backend_systems = ["Other"];
$.each(response.backend_systems, function (id,system_object) {
backend_systems.push(system_object["system"]);
});
}
$("#BackEnd").autocomplete({
source: backend_systems,
open: function(){
$(this).data("autocomplete").menu.element.addClass("backend_dropdown");
$('.backend_dropdown').width(432);
}
});
}
}
);
I also removed the prepend li
element
Upvotes: 1