I have simple jQuery UI autocomplete, which was working and now it’s not. The code is as follows:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.23.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$( "#city" ).autocomplete({
source: function( request, response ) {
var cities = new Array();
cities.push({"label" : "Chicago", "value" : 1});
cities.push({"label" : "Houston", "value" : 2});
response(cities);
},
focus: function(event, ui) {
//console.log(ui.item.label);
$(this).text(ui.item.label);
//console.log($(this).text());
event.preventDefault();
//console.log($(this).text());
},
select: function(event, ui) {
//console.log($(this).text());
event.preventDefault();
//console.log($(this).text());
}
});
});
</script>
</head>
<body>
<input id="city" />
</body>
</html>
I am using the focus handler to show the label in the textbox instead of the value (which is what the autocomplete does by default). What is happening now is that the textbox is showing neither label nor value, it is showing the value that I have typed (say ‘Chi’)
This was working but now it’s not. I thought it was because I had included some other javascript and there was a function name clash. But I moved it to a separate HTML as you can see above and it’s still not working.
BTW if I uncomment those console log statements and from the dropdown I select Chicago, then all of them print Chicago.
This seems like some silly mistake somewhere but has me stumped. Any suggestions?
EDIT 1: BTW, if I remove the focus and select handlers then the autocomplete works with its default functionality.
EDIT 2: Would be great if someone can test this on their own computer
There are a couple of changes from default functionality which you appear to be attempting here.
The reasons that neither of these are currently working are related and simple:
<input>fields only have a value associated with them, not a separate “label” and “value”. When you select an “autocomplete” option from the list, it is the “value”, which gets filled in.For point 1, the part which is being updated by the
focus:event, just replace.text(...)with.val(...), as that is the attribute of the<input>field which you actually want to update:For point 2, as you actually want the field to be filled in by the label, not the value, you could just fill in the same text for both (the default if a flat array is given):
Remember that autocomplete is always optional. All you need to fill in for the
value:is something which you back-end can fully disambiguate. That could be anid, but it usually makes sense to use something which the user might have typed in on their own. Of course, if you’re doing that, it may also make sense to useui.item.valueinstead ofui.item.labelin thefocus:event, as well.With the source made sane as above, you can drop the
select:event entirely.