I am trying to implement the autocomplete search bar similar to facebook (like the drop down results when clicked on a particular result, it should direct to the respective link).
I have got the autocomplete thing working (search results displaying only text) but I am not sure how to link the respective links/urls to the results.
Any help is much appreciated. Thank you.
Below is my searchjson method for java which I have linked to routes as 'GET' method.
public static Result searchJSON(String query) {
List<Account> userAccs = searchAccounts(query);
ObjectNode json = Json.newObject();
ArrayNode jsonArray = json.putArray("");
ObjectNode node = null;
for(Account acc : userAccs) {
node = jsonArray.addObject();
node.put("label", acc.getDisplayName());
node.put("id", acc.getId());
}
return ok(jsonArray);
Below is my javascript for autocomplete
var SearchBar = (function($) {
var search_data = function( request, response ) {
$.ajax({
url: "/search.json",
dataType: "json",
type: "GET",
data: {q: request.term },
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.label,
id: item.id
};
}));
}
});
};
$("#searchfield").autocomplete({
source: search_data,
minLength: 1
});
return {
attach: attach_to_bar
};
}) (jQuery);
On your autocomplete constructor you can use the option
select: function( event, ui ) {}
that gets fired when you select an item. So you can then do whatever you like.
So you talk about redirecting, in that case you can redirect to that page with window.location
Related
I'm facing issue with jquery autocomplete with ajax data as source. The data which is returning is proper and it is not issuing any errors. But still the results are not displaying as they should.
I have followed all the stackoverflow questions related this issue. And everything is pointing to what I have done. So it is not a duplicate of any of those questions.
If I use local variable data as data source, everything working as expected. It is not issue with UI as the same code is used for both the local variables and the ajax data.
My Code is:
$("#dTSearch").autocomplete({
source: function( request, response ) {
$.ajax({
type: "POST",
url: "{{path('dataSearch')}}",
dataType: "json",
data: {
type: "dashboardType",
searchTerm: $("#dTSearch").val()
},
success: function (data) {
if(data.status == 200) {
console.log(data.data);
//response( data.data );
//var dataSet = $.parseJSON(data);
response($.map(data.data, function (item, i) {
//alert(item.value);
return {
id: item.id,
label: item.label,
value: item.value
};
})
);
}
},
error: function (data) {
alert('error!');
console.log(data);
}
});
},
minLength: 3,
select: function( event, ui ) {
alert(ui.item.value);
return false;
},
open: function() {
$(this).autocomplete('widget').css('z-index', 100);
return false;
}
});
$("#dTSearch1").autocomplete({
source: dashboardTypes,
minLength: 3,
select: function( event, ui ) {
$("#onlyFunctionalDiv").show();
},
open: function() {
//$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
$(this).autocomplete('widget').css('z-index', 100);
return false;
}
});
I used the direct "response" method and "Map" in "Response" method. Nothing seems to be working.
When I consoled the results and put up alerts everything seems to be fine.
Below images shows the results and console logs I used.
Image 1:
Image 2:
In the first picture, the source is local variable and it is displaying the results when user start typing. Below is the console log of the same local variable.
The second picture is for the ajax response. When user types "func" it is calling the ajax and response is printing. But the results are not displaying as they should. The green color box indicates the response of a local variable and the red color box shows the ajax response data. Both seems to be same. But something is missing and it is not displaying the results when result set is available.
Can someone help me, what's wrong with this?
Issue is resolved. The problem is trailing semi-colon ";" at the end of return statement in the response method.
Changes in the code is:
response($.map(data.data, function (item, i) {
//alert(item.value);
return {
id: item.id,
label: item.label,
value: item.value
}
})
);
I have removed the trailing semi-colon at the end of the return statement.
I have the following Javascript code that works perfectly as far as the autocompleting as well as filling 5 additional input fields, based on the loaded array from MySQL in the type_code.php file.
The sixth element of the array val(names[6]) is filled with a database value of either Yes or No and I am trying to use this value to control whether an additional form field becomes readonly or readwrite at the front end.
It seems as if my if statement is badly formatted, as if I run the two lines of codes without the if everything works as expected.
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if($(val(names[6])) == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
Can someone please help me structure this if statement correctly?
Thanks,
Adri
The val() method returns or sets the value attribute of the selected elements.
Note: The val() method is mostly used with HTML form elements.
Use
if(names[6] == "Yes")
instead of
if($(val(names[6])) == "Yes")
=========================================================================
<script type="text/javascript">
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if(names[6] == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
</script>
Need following change in your code
// Code that is not working
if(names[6] == "Yes") //Change this if($(val(names[6])) == "Yes")
{
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
}
else
{
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
I use Select2-4.0.0 I have been struggling with this problem for a whole day that to update the data.
I search every posts I can like Update select2 data without rebuilding the control, but none have them work.
What I need is really simple (a setter to data):
I have a diaglog, which had a select. Every time I open the diaglog, I will ajax for an data to keep it in a local array like:
when dialog open :
var select2List=syncToLoadTheData();//data for select2
$('#search-user-select').select2({ //here when secondly executed, the select2's data on UI does not refreshed
data:select2List,
matcher: function(params, data){
var key = params.term;
if ($.trim(key) === '') {
return data;
}
if( (matchKeyAndPinyin(key,data.text))){
return data;
}
return null;
}
}
But the problem is even though the list is changing, the select options does not change at all.Please note in my test case, every time i open the dialog, the data from server is changed:
What I had tried:
1.when init:
data: function() { return {results: select2List}; }// not work to show any data at all
2.when secondly open dialog:
$( "#search-user-select").select2('data',newdata,true);//not work to have the new data
3.when secondly open:
$("#search-user-select").select2("updateResults");//Error, does not have this method
And some other method like directly change the array's data(only one copy of the data), but none of them work.
I had the same problem before, my problem was i need to update the select2 after every ajax request with new data.
and this how i fixed my code.
EventId = $(this).attr('id');
$.ajax({
url: 'AjaxGetAllEventPerons',
type: 'POST',
dataType: 'json',
data: {id: EventId},
})
.done(function(data) {
$("#select2_job").select2({
minimumInputLength: 2,
multiple:true,
initSelection : function (element, callback) {
//var data = data;
callback(data);
},
ajax: {
url: "/AjaxGetAllPersonForEvent",
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.fullname
});
});
return {
results: myResults
};
}
}
});
I hope this example will help you to solve your problem
Im using jquery Select2, select2 works perfectly fine. but what i want that when page loads a default value should be loaded from controller.
Yes i already did google and yes this question have been posted many times and i cant quite get my head around it.. so thats why i need help in this.
Here is the select2 js coding:
/*----------- Select2 DropDown Common Script -------------------------*/
//For ServerSide Script
function commonSelect2(selector,url,id,text,minInputLength,placeholder){
selector.select2({
minimumInputLength:minInputLength,
placeholder:placeholder,
ajax: {
type:"post",
url: url,
dataType: 'json',
quietMillis: 100,
data: function(term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
initSelection : function (element, callback) {
var data = {id: element.val(), text: element.val()};
callback(data);
},
results: function(data, page) {
var newData = [];
$.each(data, function (index,value) {
newData.push({
id: value[id], //id part present in data
text: value[text] //string to be displayed
});
});
return { results: newData };
}
}
});
}
and here how i calls it from php file
{{*The Selector for Selecting the User Group*}}
var selector = $('#selectGroup');
var url = "{{base_url()}}admin/usersManageUsers/loadAllUserGroups/";
var id = "GroupID";
var text = "GroupName";
var minInputLength = 0;
var placeholder = "Select User Group";
commonSelect2(selector,url,id,text,minInputLength,placeholder);
//End of the CommonSelect2 function
I have added the initselection() function, but i don't know if i did wrote it correctly?
and in end i added this in html select2 hidden input tag.
I have tried to search on net, but looks like i am getting no where.
My Mistake.
i defined initSelection inside the ajax. Should have defined it outside ajax.
now defined initSelection() after the ajax
ajax: {
type:"post",
url: url,
dataType: 'json',
quietMillis: 100,
data: function(term, page) {
return {
term: term, //search term
page_limit: 10 // page size
};
},
results: function(data, page) {
var newData = [];
$.each(data, function (index,value) {
newData.push({
id: value[id], //id part present in data
text: value[text] //string to be displayed
});
});
return { results: newData };
}
},
initSelection : function (element, callback) {
var data = {id: element.val(), text: element.val()};
callback(data);
}
I am trying to implement jQuery autocomplete using the approach illustrated below (i.e. a separate source function and an intermediary variable for the data). Right now I'm trying to get the data to the source part of the autoComplete function.
The code below works with one fatal issue, the very first key stroke returns an undefined returnData variable. Can any one explain what's going on?
var returnData;
function sourceFn() {
return $.ajax({
url: //REST URL,
dataType: "jsonp",
async: false,
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function (data) {
returnData = data;
},
})
}
}
$("input#search-input").bind("autocompleteselect", jQuery.proxy(function (event, ui) {}, this)).autocomplete({
appendTo: "#yt-result-list",
source: function (request, response) {
sourceFn(request, response).done(alert("returnData: " + JSON.stringify(returnData)));
}
}).data("autocomplete")._renderItem = jQuery.proxy(function (ul, item) {
alert(item);
}, this)
});
});
});
Try specifing the minLength: 0 when initializing the autocomplete, check the value of returnData to see if you get the json back from the server (use firebug).
Looks like you're not getting from the ajax call with one letter only, the autocomplete is triggering sourceFn() correctly.