Jquery UI Autocomplete custom data doesn't works as expected - javascript

I'm trying to make an autocomplete with custom data like JQUI docs illustrate
Here is my Javascript code :
$.ajax({
type : 'POST',
url : '/loadUserCompanyByAjax',
dataType : 'json',
success: function (result) {
if (result.error == null) {
var dataArray = [];
$.each(result.companies,function(index,element){
dataArray.push({
name : element.name,
id : element._id
});
});
$( '.companyNameFromCreateMoe:empty' ).autocomplete({
minLength: 0,
source: dataArray,
focus: function( event, ui ) {
$(this ).val( ui.item.name );
return false;
},
select: function( event, ui ) {
alert(ui.item.id);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.name +"</a>" )
.appendTo( ul );
};
}
else {
alert('AN ERROR HAS OCCURED DURING GETTING COMPANIES : ' + result.error);
}
}
});
The problem is that when i begin to type a letter nothing is happening excepted if i type the letter "e"...
And when i type the following the autocomplete list disapears..
If i change my dataArray by the Array given in exemple it works.
Here the content of my dataArray :
[
{
"name":"SARL salut ça va",
"id":"55bdd266b1257b401d405ead"
},
{
"name":"EURL Marco plomberie",
"id":"55bde8b3e633d33c1ecfbecc"
}
]

The source list objects should have the keys "label" and "value".
Read the documentation for the source property: http://api.jqueryui.com/autocomplete/
you should change your loop to create dataArray like this
$.each(result.companies, function (index, element) {
dataArray.push({
label: element.name,
value: element._id
});
});
Here is the detailed fiddle.
http://jsfiddle.net/sqfwhxmj/1/
Hope it helps.

Related

Search by category in jquery auto complete

I am using category wise jquery autocomplete https://jqueryui.com/autocomplete/#categories to show list in drop down. I pass city names as label and country name as category. search by label name works fine but I want to give option to search by country. If user type country name then all cities from the country should be shown in drop down list.
So if user type australia then I need to find all lebels with category australia and show them in drop down
I have attached image which shows current functionality
javascript code is
$( "#loading" ).catcomplete
({
source: function( request, response )
{
$.ajax({
url: 'URL to fucntion',
dataType: "json",
data: {},
async:true,
success: function(data) {
var cat_data = $.map(data, function(item) {
return {
label: item.label,
category: item.category,
};
});
$("#loading").catcomplete({
source: cat_data,
minlength:0,
delay: 0
});
}
});
},
response: function(event, ui) {
if (!ui.content.length) {
$( "#loading" ).catcomplete({
source: [{"label":"australia","category":"sydney"},{"label":"australia","category":"melbourne"}]
});
} else {
$("#message").empty();
}
}
});
Hi I solved it using following code
use value and desc in json response instead of label and category
$( "#loading" ).autocomplete({
source: Json data here,
focus: function( event, ui ) {
$( "#loading" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#loading" ).val( ui.item.desc );
$( "#loading-id" ).val( ui.item.value );
$( "#loading-description" ).html( ui.item.desc );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.desc + "</div>" )
.appendTo( ul );
};

jquery autocomplete, how to show all options on focous?

I have below autocomplete code, which works fine When i type one or more letters.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
I would like to populate the drop down with all of the matching words from the database on just focusing the input box. That means even without typing a single word. When i just focus, the function is called, but nothing within the
function $(this).autocomplete({ is executed. Any idea why autocomplete not working when focus in on the input field?
Use below code it will work as per your requirement.
$("body input.sub-category").each(function{
$(this).on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val();
$(this).autocomplete({
minLength: 0,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(".sub-cat").val(ui.item.label);
return false;
},
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
});
If this is not work add status in comment.
I was able to fix by adding one more function. So there is one function executing on keyup and another one on focus.
$("body").on('keyup', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
});
Above one executes on keyup and below one on focus.
$("body").on('focus', 'input.sub-category', function () {
var id = $(this).data('thiscatid');
var term = $(this).val()?$(this).val():"";
$(this).autocomplete({
minLength: 0,
autoFocus: true,
source: function( request, response ) {
$.post( base_url + 'ajax/getSubCats',
{ parent_id: id, term: term},
function( data ) {
response(data);
},
'json'
);
},
select:function(event,ui){
$(this).val(ui.item.label);
return false;
},
change: function(event, ui) {
if (ui.item == null) {
this.setCustomValidity("You must select a category");
}
}
});
$(this).autocomplete("search", "");
});

jQuery UI Autocomplete - Search based on a json node

I'm trying to search based on a school name, once the school name is selected populate a form.
I'm having a few issues searching on that particular jSON node, which in this case is name I have got the JSON response working, But it's just returning everything back. Not the specific term.
An example of my jSON Data :
[
{
"name":"The Mendip School",
"ta":"ta552023",
"address1":"Longfellow Road",
"address2":"Radstock",
"town":"",
"postcode":"BA3 3AL"
}
]
My jQuery is as follows :
// School Search....
var data_source = 'schools.json';
$(".school_name").autocomplete({
source: function ( request, response ) {
$.ajax({
url: data_source,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data, function ( item )
{
return {
label: item.name,
value: item.name
};
}));
}
});
},
minLength: 3,
focus: function (event, ui) {
$(event.target).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
How do I modify my JQuery to search on the name field? I will also need to get the other fields to populate input fields.
Thanks
Here is something that may suit your needs:
$("#school_name").autocomplete({
source: function ( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
$.getJSON("/schools.json?term=" + request.term, function (data) {
var x = $.grep(data, function (item, index) {
return matcher.test( item.name );
});
console.log(x);
response($.map(x, function (item) {
return {
label: item.name,
value: item.name
};
}));
});
}
The code above will filter the data using the regex(new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" )). This regex will search for names which start-begin(^) with the typed text(by the user). The 'i' in the regex is for case-insensitive while the escapeRegex will just escape any special characters in user input.
You can also use your code and do the respective changes, I think it will also work. I just prefer to use $.getJSON. Take care of the #school_name for id(in your code you are using '.')
Try it here: http://jsbin.com/vawozutepu

jquery autocomplete 'Disable' show all terms

Hey could someone guide me out of this problem....
I successfully created the jquery autocomplete function , but my problem is that autocomplete suggestions shows all the available labels . Autocomplete is showing the results which are not even matching the search term . I mean it showing all available label . Is their any solution to show only matching labels. here is the java function.
Any help will be gladly appreciated . Thank You
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data.stuff, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
EDIT : - Here is the Json File
{"stuff":[ {"label" : "Dragon", "value" : "eg.com"} ,
{"label" : "testing", "value" : "eg2.com"}]}
Successful Edited Code
<script>
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test( v.label );
});
response( $.map( sData, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
focus: function (event, ui) {
this.value = ui.item.label;
event.preventDefault(); // Prevent the default focus behavior.
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
</script>
Here is the change you want to make:
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
return v.value.indexOf( request.term ) > -1;
});
response( $.map( sData, function ( item ) {
This search will be done by value. To search by label, in other words for the user's input to be compared to the label in your JSON use the following instead:
return v.label.indexOf( ........
UPDATE
To make your search case insensitive, use the following:
var re = new RegExp( request.term, "i" );
return re.test( v.label );
instead of return v.value.indexOf( request.term ) > -1;

search matching keyword on typing anything

Iam new to programming.
Please dont mind if its a simple question.
I have a search box,
html
<input type="text" id="search" placeholder="Search" autocomplete="off"/>
When i type anything in search box, for example like abc, I need to show in dropdown as , restaurents matching 'abc', this is to be done in frontend.
Here is the code i have written to get data,
js
$("#search").keyup(function(){
if ($(this).val().length == 3) {
console.log($(this).closest(".row-fluid").find("ul").attr('id'));
$(this).closest(".row-fluid").find("ul").css('display', 'none');
}
}).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/search/site_search/"+$('#search').val(),
dataType: "json",
success: function(data) {
response( $.map( data.result, function( item ) {
return {
label: item.complaint_title,
value: item.complaint_iid,
};
}));
},
error: function(result) {
alert("Error");
}
});
},
select: function (event, ui) {
console.log(ui.item);
},
focus: function( event, ui ) {
$( "#search" ).val( ui.item.label );
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
Can anyone tell me how to do this.

Categories

Resources