Reputation: 4792
I am using Ruby on Rails 3.2.2 and the jquery-rails 2.1.3 (including jQuery UI). I am trying to implement a HTML form so to search, select and submit city data by using the Autocomplete jQuery UI widget.
At this time I am implementing my form with the following "autocompletable" field:
<div class="ui-widget">
<label for="cities">City: </label>
<input id="cities" />
</div>
<script>
$jQ(function() {
var cache = {};
$jQ( "#cities" ).autocomplete({
autoFocus: true,
minLength: 3,
source: function( request, response ) {
$jQ.ajax({
url: '<SEARCH_PATH>',
data: { search: request.term },
dataType: 'json',
success: function(data) {
var cities = new Array();
$jQ.each(data, function(arrayID, city) {
cities.push({ label: city.name, value: city.id })
});
response( cities );
},
error: function () {
response([]);
}
});
}
});
});
</script>
The above code works as expected for retrieving JSON data and displaying the list of retrieved cities. As you can see, the "useful part" of city data is the id
of the city since I am using the id
value in order to handle internally the submitted data. However, given the "selectable" list of cities is displayed, when I use keyboard UP and DOWN arrows in order to select one of those cities then the input field is populated with the city id
(not with the city name
).
I would like to:
name
instead of the id
in the input field on selecting the city;id
and not the city name
(even if the city name
is the only thing displayed in the front end content).How could / should I make to properly accomplish that?
Upvotes: 0
Views: 410
Reputation: 95048
Use the select event to populate a hidden field, then submit the hidden field instead.
<div class="ui-widget">
<label for="cities">City: </label>
<input id="cities" />
<input name="cities" type="hidden" id="cities-hidden" />
</div>
js
$jQ(function() {
var cache = {};
$jQ( "#cities" ).autocomplete({
autoFocus: true,
...
select: function(e, ui) {
$("#cities-hidden").val(ui.item.value); // populate hidden input
$("#cities").val(ui.item.label); // populate autocomplete input
return false; // prevent default action of populating autocomplete input with value
}
});
});
Demo: http://jsfiddle.net/f8yPX/3/
Upvotes: 2