Reputation: 553
I'm trying to display an auto complete text box. I'm also trying to display the city names and wanna store the corresponding cityId
of the city in another box while selecting one city.The auto complete box is working fine(I mean I'm getting the city name list).But when I select a city, its name is not showing in the box but it shows the id.
My code is given below.
<div class="col-sm-10">
<input type="text" name="txtCity" placeholder="City" id="txtCity" class="form-control">
<input type="text" name="txtCityId" placeholder="City" id="txtCityId" class="form-control">
</div>
<script type="text/javascript">
$(function() {
$("#txtCity").autocomplete({
source: 'getcitylist',
select: function (event, ui) {
$("#txtCity").html(ui.item.label); // display the selected text
// $("#txtCityId").val(ui.item.value); // save selected id to hidden input
}
});
});
</script>
This is the data base function:
public function getCityList(){
$term = Input::get('term');
$cityList = CityModel::getCityNameAjax($term);
foreach ($cityList as $key=>$value) {
$data[$key]['label']=$value->cityName;
$data[$key]['value']=$value->id;
}
echo json_encode($data);
}
Upvotes: 0
Views: 1455
Reputation: 23816
You can prevent default methods of setting value with event.preventDefault()
or you can return false
also.
Complete code:
$( "#textCity" ).autocomplete({
source: aTags,
select: function (event, ui) {
event.preventDefault(); //preventing default methods
$("#textCity").val(ui.item.label); // display the selected text
$("#textCityId").val(ui.item.value); // save selected id to hidden input
}
});
Working demo link: http://jsfiddle.net/9R4cV/806/
Upvotes: 1