Reputation: 1077
I have the following jquery autocomplete which does work.
<input type="hidden" id="autocompletePid" autocomplete="off" />
The relevant JS
<script type="text/javascript">
$(function() {
$("#autocomplete").autocomplete(
{
source : function(request, response) {
$.ajax({
type : 'GET',
url : "/live-search" + '?term=' + request.term,
success : function(data) {
response($.map(data, function(item) {
return {
label : item.street + ' '
+ item.city.city + ', '
+ item.state.stateCode
+ ' '
+ item.zipcode.zipcode,
value : item.pid
}
}));
},
minLength : 3
})
}
});
});
</script>
The relevant HTML
<div id="tabs-1" class="ui-tabs-hide">
<input type="text" id="autocomplete" autocomplete="off"
placeholder="Enter an address or city..." /> <input
type="submit" value="GO" />
</div>
The issue I'm facing is that with the current code, the value gets changed to pid
which would make no sense to the user. I added a hidden input and I want to change the value of the hidden input.
<input type="hidden" id="autocompletePid" autocomplete="off" />
How would I do that?
Upvotes: 0
Views: 3195
Reputation: 3006
Try the below code:
<script type="text/javascript">
$(function() {
//Create a array call 'auto_array'
var auto_array = {};
var label = '';
$("#autocomplete").autocomplete(
{
source : function(request, response) {
$.ajax({
type : 'GET',
url : "/live-search" + '?term=' + request.term,
success : function(data) {
response($.map(data, function(item) {
label = item.street + ' '+ item.city.city + ', '+ item.state.stateCode + ' '+ item.zipcode.zipcode;
//Put the id of label in to auto_array. use the label as key in array
auto_array[label] = item.pid;
return label;
}));
},
})
},
minLength : 3,
//On select the label get the value(id) from auto_array and put in hidden input field 'autocompletePid'
select: function(event, ui) {
console.log(auto_array);
$('#autocompletePid').val(auto_array[ui.item.value]);
}
});
});
</script>
Upvotes: 1
Reputation: 3104
Steps:
Change your return value to save the pid. set label and value to be your displayed value:
var label = item.street + ' '
+ item.city.city + ', '
+ item.state.stateCode
+ ' '
+ item.zipcode.zipcode;
return {
label : label,
value : label,
pid : item.pid
}
Bind to select
function from autocomplete to set the value to a different field as you desired
select: function (event, ui) {
$(autocompletePid).val(ui.item ? ui.item.pid : "");
}
Here's the full working fiddle: https://jsfiddle.net/q9zyejd0/16/. Notes:
select
won't trigger when you delete a value from your text box. You should either manually bind to change
(which will make the hidden field be updated when you focus out of the text field, a little uglier, but works better), or manually fix it with $(autocomplete).focusout
.Upvotes: 0