I have a form that load Jquery autocomplete, I got the result, but it does not shows up (blank with border). Just like this image:
Here's my JQuery Code:
<script type="text/javascript">
// Customer
$('input[name=\'customer\']').autocomplete({
delay: 500,
source: function (request, response) {
$.ajax({
url: 'getCustomer.php?filter_name=' + encodeURIComponent(request.term),
dataType: 'json',
success: function (json) {
response($.map(json, function (item) {
return {
label: item.c_name,
value: item.c_id
}
}));
}
});
},
select: function (event, ui) {
$('input[name=\'customer\']').val(ui.item.label);
$('input[name=\'customer_id\']').val(ui.item.value);
return false;
},
focus: function (event, ui) {
return false;
}
});
</script>
And here's AJAX result:
Anyone here have same problem before? I'm using Admin LTE template by the way. And still wondering what's wrong with my code. I have tried import other Jquery-min-js but still not working. Still displayed like that (blank bordered). FYI: there's no error at console log.
I am guessing that the AJAX response you've shown (as an image) is the actual response from the server, before your $.map() has modified it.
Your $.map() function iterates over that json response from the server, and it tries to use the c_name and c_id property names in each element. But the json from the server does not include those property names - it has customer_id and name.
So the $.map() creates a bunch of empty elements, and passes them on to autocomplete. Autocomplete then has a set of elements to display, but without any labels, which is why you see the dropdown with empty horizontal lines, rather than just nothing at all, which is what you'd see when there's no response/match at all.
You simply need to use the same property names you have in your AJAX:
response($.map(json, function (item) {
return {
label: item.name,
value: item.customer_id
}
}));
Related
I am using the jQuery autocomplete plugin. The situation is that the hint data is taken via the GET API method. I can't make the code wait until the end of accepting data from the API.
$('#vehicleBrand').autocomplete({
source: function(request, response) {
$('#vehicleBrandValue').val('');
$.get('api/brands', {
query: request.term,
category: $('select[name="vehicleType"]').val()
}, function(data) {
response(data)
})
},
select: function(event, ui) {
$('#vehicleBrandValue').val(ui.item.data);
event.target.classList.remove('border-danger');
prepareModels(ui.item.data);
},
close: function(event, ui) {
if (!$('#vehicleBrandValue').val()) {
alertify.error('Error text here!');
event.target.value = '';
event.target.classList.add('border-danger');
event.target.focus();
}
}
});
In the code above, on the source key, I call the get method to get the data.
let brand = data.car_brand;
$('#vehicleBrand').data("ui-autocomplete").search(brand)
$("#vehicleBrand").data("ui-autocomplete").menu.element[0].firstChild.click()
In the code above I am looking for a car brand and click on it through the script. But the click occurs before the request for data on the source key has time to complete, and the click occurs in the undefined list.
Where can I make the click wait for a response from the function by the key source ?
I tried to use Promise and async/await in function by key source, but it didn't work
Might advise the following:
$('#vehicleBrand').autocomplete({
source: function(request, response){
$.getJSON('api/brands', {
query: request.term,
category: $('select[name="vehicleType"]').val()
}, function(data){
response(data);
});
},
select: function(event, ui) {
$('#vehicleBrandValue').val(ui.item.value);
$(this).removeClass('border-danger');
prepareModels(ui.item.label);
},
close: function(event, ui) {
if (!$('#vehicleBrandValue').val()) {
alertify.error('Error text here!');
$(this).val("").addClass('border-danger').focus();
}
}
});
Need to also make sure that you have { label, value } pair someplace in your data results.
See more: https://api.jqueryui.com/autocomplete/#option-source
Using $.getJSON() is short hand for a AJAX GET Request that is expecting JSON data as a result.
If you are later using this code:
let brand = data.car_brand;
$('#vehicleBrand').data("ui-autocomplete").search(brand)
$("#vehicleBrand").data("ui-autocomplete").menu.element[0].firstChild.click()
The code will execute right away, before results have loaded. You may need to delay the trigger using setTimeout since there is not a Promise to execute after. Something like this might work:
$('#vehicleBrand').autocomplete("search", data.car_brand);
setTimeout(function(){
$("#vehicleBrand").autocomplete("widget").find(".ui-menu-item:eq(0)").trigger("click");
}, 1200);
This give Autocomplete time to load the events before triggering a click event.
Using select2.js to retrieve remote data bound to a hidden input.
<input type="hidden" id="departmentNameEntry" style="width:300px"/>
I have set the placeholder in the initialization:
$("#departmentNameEntry").select2({
placeholder: "Search for a department",
minimumInputLength: 2,
ajax: {
url: "Handlers/DeptNameSearch_handler.ashx",
cache: false,
dataType: 'json',
type: 'GET',
data: function (term, page) {
return {
departmentNameFragment: term // search term entered into querystring for handler
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
return { results: data };
}
},
formatResult: function (item) {
return item.text;
},
formatSelection: formatDepartmentNames,
formatNoMatches: function (term) {
return 'no department name matches your query';
}
});
But as soon as an item is selected, the placeholder goes blank. How can I reset it to the original string? I have tried placing the init code in a separate function and execing it again, but no joy. Other questions I have seen answered seem to be specific to binding to a SELECT. What am I doing wrong?
I didn't RTFM closely enough.
The formatSelection option requires you to return a string that is then displayed in the select2 in place of the placeholder text. Here is my function:
function formatDepartmentNames(dept) {
$('#hfDepartmentID').val(dept.id); // when user has selected from the list, put id in an input
$('#hfDepartmentName').val(dept.text); // stash the dept name for later
DepartmentCurrentBossesGet(dept.id, dept.text); // call another function
DepartmentBossHistoryGet(dept.id); // call yet another function
$('.row4').show(); // show useful data on the page
return dept.text; // return the dept name so select2 can display it
}
Hopes this helps someone.
I'm using select2 in order to create styled select boxes with autocomplete. I have 2 choices, load the data from a json file, or create a simple array from that json and use a workaround to populate the select tag. I read through their api examples but obviously I'm missing something. My goal is to create a drop down list with many elements, the problem is that the data is a huge array, which consists of aprox 15k cells. I tried a workaround using this code:
HTML:
<select multiple="multiple" data-placeholder="Select item" id="itemsList">
JS:
var list = $("#itemsList");
var txt = "";
for(var i=0;i<itemsArray.length;i++){
txt =txt+ '<option value='+itemsArray[i]+'>'+itemsArray[i]+'</option>';
}
list.append(txt);
This works, but obviously select2 manages things more efficiently, as this "method" takes several good seconds to load the data in to the DOM.
The second approach is to load the json straight to the select2 box and let the framework to manage the construction, but this leads me to an error: Cannot read property 'slice' of undefined.
JSfiddle here
This is the code:
HTML:
<div class="input-group" id="itemContainer">
<label> Select an item: </label>
<select multiple="multiple" data-placeholder="Items list" id="itemList">
</select>
</div>
JS:
$("select").select2({
ajax: {
//this is a small demo json to illustrate its structure
url: "https://api.myjson.com/bins/5amne",
dataType: 'json',
delay: 0,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
console.log(data);
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
Your processData function should handle custom data format, e.g. parse it in a way that is understandable by the select2. Here's how it can be done:
processResults: function (data) {
var results = $.map(data, function (value, key) {
return {
text: key,
children: $.map(value, function (v) {
return {
id: v,
text: v
};
})
};
});
return {
results: results,
};
},
See the updated JSFiddle
Edit
If you want the select2 to handle filtering for you, there are two ways of doing that:
Adding server-side support;
Handling everything on the client.
Since you're loading data via from a static JSON file, you need to go #2. In order to do that, you first need to load all the data, parse it, and only then initialize the select2 control. You can do it like this:
function processData(data) {
return $.map(data, function (value, key) {
return {
text: key,
children: $.map(value, function (v) {
return {
id: key + v,
text: v
};
})
};
});
}
function initSelect2(data) {
$("select").select2({
data: data
});
}
$.ajax({
url: "https://api.myjson.com/bins/1n1rm",
dataType: 'json',
cache: true,
success: function (data) {
initSelect2(processData(data));
}
});
In order to use json for select2, the json format should be something like this:
{ results: [ {id:'first', text:'a'}, {id:'second', text: 'b'} ]
, more: false }
JSON format for jquery-select2 multi with ajax
Your current json doesn't seem to have the right format. I think you should change your json format.
Array with hardcoded object shows up in my ng-repeat.
$scope.deltagarelist = [{ label: "Nils", value: "3" }];
This is my javascript/angular hybrid code to get selected values from the autocomplete and push it into my objectarray.
$(".addDeltagare").autocomplete(
{
source: function (request, response) {
$.ajax({
url: url,
data: { query: request.term },
datatype: 'jsonp',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Label,
value: item.Value
}
}));
}
});
},
minLength: 3,
select: function (event, ui) {
event.preventDefault();
addtolist(ui.item);
console.log($scope.deltagarelist);
$(this).val('');
},
focus: function (event, ui) {
$("#addDeltagare").val(ui.item.label);
return false;
}
});
And my function to push the object into my list.
function addtolist(item) {
$scope.deltagarelist.push({label:item.label,value:item.value});
}
My problem is that my hardcoded guy "Nils" gets a $$hashkey but when I add an object to the list in this way it doesnt get a hashkey and it adds to the array but doesnt show up in my repeat.
Any ideas on how I can change this code to make it work?
Or should I look for other autcompletes thats more "the angular way" ?
The solution is adding a track by to your ng-repeat so that AngularJS doesn't need to use the $$hashkey to track changes.
<div ng-repeat="val in deltagarelist track by val.value">
The $ajax is asynchronous, this means the NG-app is already been build before the data is downloaded. A workaround is to make $ajax sync sothat everything waits until the data is downloaded.
I am working on an ASP.NET MVC 4 app. In my app, I'm trying to replace my drop down lists with the Select 2 plugin. Currently, I'm having problems loading data from my ASP.NET MVC controller. My controller looks like this:
public class MyController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<MyItem>))]
public IHttpActionResult Get(string startsWith)
{
IEnumerable<MyItem> results = MyItem.LoadAll();
List<MyItem> temp = results.ToList<MyItem>();
var filtered = temp.Where(r => r.Name.ToLower().StartsWith(startsWith.ToLower());
return Ok(filtered);
}
}
When I set a breakpoint in this code, I notice that startsWith does not have a value The fact that the breakpoint is being hit means (I think) my url property below is set correct. However, I'm not sure why startsWith is not set. I'm calling it from Select 2 using the following JavaScript:
function formatItem(item) {
console.log(item);
}
function formatSelectedItem(item) {
console.log(item);
}
$('#mySelect').select2({
placeholder: 'Search for an item',
minimumInputLength: 3,
ajax: {
url: '/api/my',
dataType: 'jsonp',
quietMillis: 150,
data: function (term, page) {
return {
startsWith: term
};
},
results: function (data, page) {
return { results: data };
}
},
formatResult: formatItem,
formatSelection: formatSelectedItem
});
When this code runs, the only thing I see in the select 2 drop down list is Loading failed. However, I know my api is getting called. I can see in fiddler that a 200 is coming back. I can even see the JSON results, which look like this:
[
{"Id":1,"TypeId":2,"Name":"Test", "CreatedOn":"2013-07-20T15:10:31.67","CreatedBy":1},{"Id":2,"TypeId":2,"Name":"Another Item","CreatedOn":"2013-07-21T16:10:31.67","CreatedBy":1}
]
I do not understand why this isn't working.
From the documentation:
Select2 provides some shortcuts that make it easy to access local data
stored in an array...
... such an array must have "id" and "text" keys.
Your json object does not contain "id" or "text" keys :) This should work though i have not tested it:
results: function (data, page) {
return { results: data, id: 'Id', text: 'Name' }
}
There's further documentation following the link on alternative key binding... I believe thats where your problem lies.
Hopefully this helps.