Why jQuery autocomplete select not work? - javascript

When I input 5 in the customer_code input area. It list the values.The problem is that when I select an entry, the 'id' value should show in the customer_name area.But it didn't!
[{"id":"5","code":"code005","name":"\u9867\u5ba2\u540d005"},{"id":"15","code":"code015","name":"\u9867\u5ba2\u540d015"},]
the json return by php is like above.and
$(function() {
$( "#customer_code" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/management/order/auto",
dataType: "json",
data: {code: request.term},
success: function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.code,
// label: val.name,
});
});
response( suggestions );
},
});
},
select: function(e, ui) {
alert(ui.item.name);
// $('#customer_name').val(ui.item.name);
// $('#customer_name').val(ui.item.value.name);
// return false;
},
});
});
my html page is like this
<?php echo Form::input('customer_name', Arr::get($basic, 'customer_name'), array('id' => 'customer_name')); ?>
<?php echo Form::input('customer_code', Arr::get($basic, 'customer_code'), array('id' => 'customer_code')); ?>

The select callback is currently part of the settings for the $.ajax() request, which won't use it:
// ...
$.ajax({
url: "/management/order/auto",
// ...
success: function (data) {
// ...
},
select: function (e, ui) {
// ...
}
});
// ...
It should instead be part of the options for .autocomplete(), outside of the function for source.
$( "#customer_code" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/management/order/auto",
// ...
success: function () {
// ...
}
});
},
select: function (e, ui) {
// ...
}
})

Related

jquery json data autocomplete not working

I'm facing an issue with jquery autocomplete. I need that after autocompleting the results on click it converts to a link with item.value:
My actual json encode return is:
[{value: "34"}, {label: "Producto 12"}]
$(function() {
$("#producto").autocomplete({
select: function (e, ui) {
$("#producto").val(ui.item.label);
window.location.href = item.value;
return false;
},
source: function (request, response) {
$.ajax({
url: "<?php echo base_url('index.php/vista/autocompletar'); ?>",
data: request,
success: function (data) {
var ParsedObject = $.parseJSON(data);
response($.map(ParsedObject, function (item) {
return {
label: item.label,
};
}))
}
});
}
});
});
Solution:
Changed the json encode to work like this:
{value: "14", label: "afasdasd"}
And did changed the autocomplete jquery code for this one:
$(function(){
$("#producto").autocomplete({
source: "<?php echo base_url('index.php/vista/autocompletar'); ?>",
minLength: 2,
select : function(event, ui){
// convierto en link el resultado y al hacer click me dirija a la vista del producto
location.href = "<?=base_url()?>index.php/vista/detalle/" + ui.item.value;
}
});
});

Cant push autocomplete selected value to global array in JavaScript

Im working on a project in which I have autocomplete with users list.
when I try to push autocomplete selected value to global array I get an empty list when I do console.info(usernames) outside autocomplete function.
var usernames=[];
$(document).ready(function(){
$(function(){
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "getUserFromDb.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event,ui){
usernames.push(ui.item.value);
}
});
console.info(usernames);
});
});
soruce of autocomplete is returning correct list and select works as well, because if I do console.info(usernames) inside autocomplete select: the list will update when im selecting different values.
Since you needed an "answer", here we go. First off, your console.info has run as soon as the DOM is ready and obviously empty as the user names are pushed in later on, when you select options from autocomplete. Secondly, you are not re-logging usernames as and when it's populated. So, you have 2 options.
1) log usernames within the select function, such as:
select: function(event,ui) {
usernames.push(ui.item.value);
console.info(usernames);
}
2) Have a function that would do the job for you, such as:
select: function(event,ui) {
usernames.push(ui.item.value);
showMeUserNames();
}
function showMeUserNames() {
console.info(usernames);
}
So, your code may become:
var usernames=[];
$(function(){
$( "#users" ).autocomplete({
source: function( request, response ) {
$.ajax({
type: "GET",
url: "getUserFromDb.php",
dataType: "json",
data: {
term: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 2,
select: function(event,ui) {
usernames.push(ui.item.value);
console.info(usernames);
// OR
// showMeUserNames();
}
});
});
function showMeUserNames() {
console.info(usernames);
}

Jquery autocomplete with label and links

I have jquery autocomplete working perfect for label and it's value.
$( "#search_name" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "/ajax/fetch_search_suggestion",
dataType: "json",
type: "POST",
data: {
keyword: request.term
},
success: function(data) {
response( $.map( data, function( item ) {
return {
label: item.label
}
}));
}
})
}
});
PHP
while($search = $result->fetch()){
$link = '';
$link .= $search['cus_firstname'].' '.$search['cus_lastname'];
array_push($searchArray, array('label'=> $link, 'value' => $keyword));
}
array_push($searchArray, array('label'=>"Not Here? Click to add new", 'value' =>"http://www.google.com"));
If customer is not there, on click add new it should go to the google.com. How can I achieve this? Thanks.
I tried with adding:
select : function(event, ui) {
response( $.map( data, function( item ) {
return {
window.location = (ui.item.value);
return false;
}
}));
}
But, I am getting error.

how enable a button if entered text is valid for autocomplete function?

i have a textbox with autocomplete feature,and a button.I want to enable the button only when a value is selected from the autocomplete list.
how to do this?
Here is my autocomplete function:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=xyz.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebService.asmx/Get") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); });
});
</script>
In your select function add this:
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
$("#buttonid").prop("disabled", true); // true disabled, false enabled
},
EDIT:
$("#buttonid").prop("disabled", false); // this put button enabled
JsFiddle - Example
For a plain button you'll want to set the the button as disabled when the document loads, e.g.
$(document).ready(function () {
$('#btn')[0].disabled = true;
...
and then enable it with the select function, e.g.
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
$('#btn').disabled = false; // <-- enables button
},
Try This: The following will be called when you perform select (use keyboard to select, dont know about mouse select)
$( "#<%=xyz.ClientID %>"" ).on( "autocompleteselect", function( event, ui ) {
$("#buttonid").prop("disabled", false);
});

How to populate extra fields with jQuery autocomplete

I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}

Categories