How can I custom-format the Autocomplete plug-in results?
Yes, you can if you monkey-patch autocomplete.
In the autocomplete widget included in v1.8rc3 of jQuery UI, the popup of suggestions is created in the _renderMenu function of the autocomplete widget. This function is defined like this:
_renderMenu: function( ul, items ) {
var self = this;
$.each( items, function( index, item ) {
self._renderItem( ul, item );
});
},
The _renderItem function is defined like this:
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
},
So what you need to do is replace that _renderItem fn with your own creation that produces the desired effect. This technique, redefining an internal function in a library, I have come to learn is called monkey-patching. Here's how I did it:
function monkeyPatchAutocomplete() {
// don't really need this, but in case I did, I could store it and chain
var oldFn = $.ui.autocomplete.prototype._renderItem;
$.ui.autocomplete.prototype._renderItem = function( ul, item) {
var re = new RegExp("^" + this.term) ;
var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" +
this.term +
"</span>");
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + t + "</a>" )
.appendTo( ul );
};
}
Call that function once in $(document).ready(...)
.
Now, this is a hack, because:
there's a regexp obj created for every item rendered in the list. That regexp obj ought to be re-used for all items.
there's no css class used for the formatting of the completed part. It's an inline style.
This means if you had multiple autocompletes on the same page, they'd all get the same treatment. A css style would solve that.
...but it illustrates the main technique, and it works for your basic requirements.
updated working example: http://output.jsbin.com/qixaxinuhe
To preserve the case of the match strings, as opposed to using the case of the typed characters, use this line:
var t = item.label.replace(re,"<span style='font-weight:bold;color:Blue;'>" +
"$&" +
"</span>");
In other words, starting from the original code above, you just need to replace this.term
with "$&"
.
EDIT
The above changes every autocomplete widget on the page. If you want to change only one, see this question:
How to patch *just one* instance of Autocomplete on a page?
Formatting the jQuery UI autocomplete results in a table
Have you thought at all about using a fixed with font (courier, maybe) and then padding your name field?
That should line things up nicely.
Something like:
$maxWidth = 30;
$nameWidth = strlen(lastname) + strlen(firstname) + 2 //don't forget the comma and space
$padding = $maxWidth - $nameWidth;
Then just pad the last name, first name with the calculated amount and things should line up.
jQuery UI - Formatting the autocomplete results. Add image possible?
There is some documentation on JqueryUI website on how to customize the result layout:
http://jqueryui.com/demos/autocomplete/#custom-data.
Some example:
$( "#SearchInput" ).autocomplete({ .... }).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + "<img src='" + item.imgsrc + "' />" + item.id+ " - " + item.label+ "</a>" )
.appendTo( ul );
};
How can I format Custom Data and display in autocomplete when source is an DB
OK so I found the answer for the question, here it is:
in the buscar.php, I only had to add a variable with the name I wished to receive in the JQ:
<?php
$conec = mysql_connect(localhost, root, admin);
if(!$conec)
{
die(mysql_error());
}
else
{
$bd = mysql_select_db("ve_test",$conec );
if(!$bd)
{
die(mysql_error());
}
}
$termino = trim(strip_tags($_GET['term']));//Obtener el termino que envia el autocompletar
$qstring = "SELECT name, descripcion FROM VE_table WHERE name LIKE '%".$termino."%'";
$result = mysql_query($qstring);//Solicitud a la Base de Datos
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//Realizar un LOOP sobre los valores obtenidos
{
$row['value']=htmlentities(stripslashes($row['name']));
$row['desc']= htmlentities(stripcslashes($row['descripcion'])); //This is the line I Changed
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//Enviar los datos al autocompletar en codificacion JSON, Altamente Necesario.?>
And this is the JQ I used:
$(document).ready((function(){
$( "#completa" ).autocomplete({
source: "buscar.php",
minLength: 1,
focus: function( event, ui ) {
$( "#completa" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#completa" ).val( ui.item.value );
$( "#completa-description" ).html( ui.item.desc );
return false;
}
})
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.value + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
}));
I hope this helps somebody else too.
When JQuery UI Autocomplete with Categories, how do I custom format the different categories?
Your initial jsfiddle works, you just needed to add jQuery script
. Here are a couple ways of finding the li
's text using .filter()
:
$('.ui-autocomplete-category').filter(':contains(Vendors)').addClass('ui-auto-vendors');
DEMO:
http://jsfiddle.net/dirtyd77/RhHpd/3/
$('.ui-autocomplete-category').filter(function() {
return $.text([this]) == 'Vendors';
}).addClass('ui-auto-vendors');
DEMO:
http://jsfiddle.net/dirtyd77/RhHpd/4/
Jquery autocomplete - custom html for result listing
You need to replace the _renderItem
method (for the autocomplete in question):
$("selector").autocomplete({ ... })
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a class='myclass' customattribute='" + item.customattribute + "'>" + item.label + "</a>" )
.appendTo( ul );
};
(assuming the items
in your source
have a property called customattribute
)
As shown in this example: http://jqueryui.com/demos/autocomplete/#custom-data
Limit the result in jQuery Autocomplete
Final Update
after understanding that in my previous answers i was limiting the whole xml result set and not the results of the autocomplete
As you have overridden the default _renderItem
method, you can override the default _renderMenu
.
$.ui.autocomplete.prototype._renderMenu = function( ul, items ) {
var self = this;
$.each( items, function( index, item ) {
if (index < 10) // here we define how many results to show
{self._renderItem( ul, item );}
});
}
answer is modified from this jQueryUI: how can I custom-format the Autocomplete plug-in results? so thanks go to @cheeso..
Original Answer
In you success
callback use $("SearchModel:lt(10)", xmlResponse).map(...
The :lt(10)
gets elements with an index of less than 10. So max 10 results will be returned..
(of course the number 10 could be anything you want)
Look at :lt()
selector at http://api.jquery.com/lt-selector/
update
Although i cannot understand why the first answer does not work, since the SearchModel
is a tag and we target that.. we can move the filtering in the map method..
success: function(xmlResponse) {
var data = $("SearchModel", xmlResponse).map(function(index) {
if (index<10)
{
return {
value: $("Name", this).text() + ", " + $("Description", this).text(),
id: $("No", this).text(),
name: $("Name", this).text(),
url: $("URL", this).text()
};
}
else
{ return null; }
}).get();
documentation of map()
How to manipulate jquery autocomplete plugin to get both the id and the value
I think what you're after is the select
option.
Let's say your data source is the following array of objects:
var data = [
{
label: 'Product 1',
productid: '1'
},
{
label: 'Product 2',
productid: '2'
},{
label: 'Product 3',
productid: '1'
}];
By default the plugin will look for the label and value property in your object (if the "value" is missing, it will use the "label").
Note: that if you provide a value, it will be used to set the value of the input when you select a suggested item in the menu !
So our example, the property productid
will actually not be used by directly the plugin, it does not know about it, but we will have access to it in the event handlers parameter ui.item
.
What I would do is add an hidden field to store the actual selected value (and not the attribute "productid" like you suggest in your question).
<input type="hidden" id="productid" value="" />
The js code:
$("#myinput").autocomplete({
source: data,
// the 'select' event is triggered when an item is selected in the menu
select: function(e, ui) {
$("#productid").val(ui.item.productid);
// if you want to add the "productid" attiubte
$(this).attr('productid', ui.item.productid);
}
});
Working DEMO
Related Topics
Make React Useeffect Hook Not Run on Initial Render
JavaScript Swap Array Elements
Get Hours Difference Between Two Dates in Moment Js
JavaScript Asynchronous Return Value/Assignment with Jquery
Why Does (0 < 5 < 3) Return True
How to Format/Tidy/Beautify in JavaScript
Bootstrap 4 Navbar Not Collapsing on Large Screen
Angularjs: Better Way to Watch for Height Change
How to Exchange Variables Between Two HTML Pages
Why How to Use a Function Before It's Defined in JavaScript
How to Validate Date with Format "Mm/Dd/Yyyy" in JavaScript
Remove All Elements Contained in Another Array
JavaScript Removeeventlistener Not Working
Jquery $("#Radiobutton").Change(...) Not Firing During De-Selection