Search by category in jquery auto complete - javascript

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 );
};

Related

Jquery UI Autocomplete custom data doesn't works as expected

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.

How make textbox readonly after filled with autocompleted value using jquery?

Here I've a textbox, its data is filled by autocomplete using JSON.
Here i want textbox readonly after selecting any value of autocomplete (suggested fields).
textbox code:
$(document).ready(function ()
{
$('#patient_id').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'opdpatientajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patientname',
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("|");
console.log(names[1], names[2], names[3]);
$('#patientAddress').val(names[1]);
$('#patientSex').val(names[2]);
$('#patientAge').val(names[3]);
}
});
});
<input type="text" id="patient_id" name="patient_nm"
placeholder="Enter and select Mother Name" title="Please Enter and select patinet name">
$("#patientAddress").attr("disabled", "disabled");
If you want to submit the field to $_POST, you need to enable it before sending the form.
$(document).ready(function ()
{
$('#patient_id').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'opdpatientajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patientname',
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("|");
console.log(names[1], names[2], names[3]);
$('#patientAddress').val(names[1]);
$('#patientSex').val(names[2]);
$('#patientAge').val(names[3]);
$("#patientAddress").attr("disabled", "disabled");
$("#patientSex").attr("disabled", "disabled");
$("#patientAge").attr("disabled", "disabled");
}
});
});
OR you can use this method:
$( "#other" ).click(function() {
$( "#target" ).blur();
});

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.

How to open the Jquery autocomplete with a fetching results status bar

I'm using the JqueryUI autocomplete. Sometimes the fetching of results isn't immediate so I'd like to notify the user the autocomplete is fetching options that match his query.
My Code:
$( "#searchid" ).autocomplete({
source: "/autocomplete_url.php",
minLength:3,
select: function(event, ui) {
event.preventDefault();
$("#searchid").val(ui.item.value);
$("#formid").submit();
}
});
How can I make the autocomplete to open a 'fetching results status bar' when sending a request to the web-service that is working on finding the results?
This approach assumes you're using an Ajax call to retrieve your dataset, but I've used something similar and it worked ok.
Set up a div on the page where you want the message.
HTML:
<div id="AutocompleteStatus" style="display:none">Loading data...please wait</div>
You then want to catch the key up event on your autocomplete:
jQuery:
$( "#searchid" ).keyup(function() {
$('#AutocompleteStatus').show();
});
Then your autocomplete could look something like this:
$( "#searchid" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "/autocomplete_url.php",
dataType: "json",
data: {
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
$("#AutocompleteStatus").hide(); // <== HIDE IT HERE
response( $.map( data.returndata, function( item ) {
return {
label: item.name,
value: item.value
}
}));
}
});
}, minLength:3,
select: function(event, ui) {
event.preventDefault();
$("#searchid").val(ui.item.value);
$("#formid").submit();
}
});
So the short version: Key up on your search box shows the div, on the return from your Ajax call (I'm using sample parameter names, your example didn't give any actual names), just hide the div again.

jQuery UI not autocompleting from JSON

When I look the response from Chrome Developer Tools I see this:
[{
"summary": "foo",
"key": "myKey"
}]
My javascript(UPDATED):
jquery183(function() {
jquery183( "#city" ).autocomplete({
source: function( request, response ) {
jquery183.ajax({
url: '/servlet/ajax/',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( jquery183.map( data, function( issue ) {
return {
label: issue.summary + ", " + issue.key,
value: issue.summary
}
}));
}
});
},
minLength: 2,
open: function() {
jquery183( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
jquery183( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
HTML:
<div class="ui-widget">
<label for="city">Your city: </label>
<input id="city" />
Powered by geonames.org
</div>
I thought this should work, but it does not suggest any autocomplete items. Any suggestions?
If more code needed, feel free to ask.
As seen on: http://jqueryui.com/autocomplete/#remote-jsonp
You forgot to copy/paste the ajax call to retrieve your data.
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://ws.geonames.org/searchJSON",
dataType: "jsonp",
success: function( data ) {
response( $.map( data.geonames, function( item ) {
return {
label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
value: item.name
}
}));
}
});
}
});
I am not sure but is there a problem with <input id="city" />. It should probably be <input id="city" type="text"/>
Found answer from here:
Ajax success event not working
The result is probably not in JSON format, so when jQuery tries to parse it as such, it fails. You can catch the error with error: callback function.
You don't seem to need JSON in that function anyways, so you can also
take out the dataType: 'json' row.

Categories

Resources