How to customize autocomplete listing view using jquery? - javascript

I am using Autocomplete jquery UI and autocomplete is working fine.
But Now i want to customize listing view(like: when i press j in textbox related data from j keyword will show customized div container).
Code what i have done :
$(document).ready(function() {
var projects = [{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library"
}, {
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery"
}, {
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine"
}];
$("#search").autocomplete({
minLength: 0,
source: projects,
focus: function(event, ui) {
console.log(ui.item.label);
$("#project").val(ui.item.label);
return false;
},
select: function(event, ui) {
console.log(ui);
$("#search").val(ui.item.label);
$("#project-id").val(ui.item.value);
$("#project-description").html(ui.item.desc);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
And This function is not working at my end :
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
I want to show a another div and in this i want to show listing of data and when mouse over on this right hand another div and open this data.
Like this :
<div class="left_div">
<ul>
<li>Android</li>
<li>Java</li>
</ul>
</div>
<div class="right_div">
<p>Android is a mobile operating system (OS) currently developed by Google</p>
</div>

Related

jQuery - Duplicate Fields & Autocomplete

I have a form with duplicate fields including autocomplete input.
The issue is : when i duplicate the fields, the autocomplete doesn't work on the new fields.
I spent time googling my issue and often it's a clone('true') issue, which i don't use already and still have the problem.
Can you help me please ? Thanks a lot !
I made a JSFiddle : https://jsfiddle.net/vqnaedvx/
Try with the letter j or s
HTML :
<div id="projects" class="content">
<button type="button" id="btnAdd" class="btn btn-primary btn-sm">Add Project</button>
<div class="row form-group group">
<input class="project-label">
<input type="hidden" class="project-id">
<button type="button" class="btn btn-danger btnRemove">Remove</button>
</div>
</div>
JS Multifield :
/**
* jQuery Multifield plugin
*
* https://github.com/maxkostinevich/jquery-multifield
*/
;(function ( $, window, document, undefined ) {
// our plugin constructor
var multiField = function( elem, options ){
this.elem = elem;
this.$elem = $(elem);
this.options = options;
// Localization
this.localize_i18n={
"multiField": {
"messages": {
"removeConfirmation": "Are you sure you want to remove this section?"
}
}
};
this.metadata = this.$elem.data( 'mfield-options' );
};
// the plugin prototype
multiField.prototype = {
defaults: {
max: 0,
locale: 'default'
},
init: function() {
var $this = this; //Plugin object
// Introduce defaults that can be extended either
// globally or using an object literal.
this.config = $.extend({}, this.defaults, this.options,
this.metadata);
// Load localization object
if(this.config.locale !== 'default'){
$this.localize_i18n = this.config.locale;
}
// Hide 'Remove' buttons if only one section exists
if(this.getSectionsCount()<2) {
$(this.config.btnRemove, this.$elem).hide();
}
// Add section
this.$elem.on('click',this.config.btnAdd,function(e){
e.preventDefault();
$this.cloneSection();
});
// Remove section
this.$elem.on('click',this.config.btnRemove,function(e){
e.preventDefault();
var currentSection=$(e.target.closest($this.config.section));
$this.removeSection(currentSection);
});
return this;
},
/*
* Add new section
*/
cloneSection : function() {
// Allow to add only allowed max count of sections
if((this.config.max!==0)&&(this.getSectionsCount()+1)>this.config.max){
return false;
}
// Clone last section
var newChild = $(this.config.section, this.$elem).last().clone().attr('style', '').attr('id', '').fadeIn('fast');
// Clear input values
$('input[type=text],input[type=hidden],textarea', newChild).each(function () {
$(this).val('');
});
// Fix radio buttons: update name [i] to [i+1]
newChild.find('input[type="radio"]').each(function(){var name=$(this).attr('name');$(this).attr('name',name.replace(/([0-9]+)/g,1*(name.match(/([0-9]+)/g))+1));});
// Reset radio button selection
$('input[type=radio]',newChild).attr('checked', false);
// Clear images src with reset-image-src class
$('img.reset-image-src', newChild).each(function () {
$(this).attr('src', '');
});
// Append new section
this.$elem.append(newChild);
// Show 'remove' button
$(this.config.btnRemove, this.$elem).show();
},
/*
* Remove existing section
*/
removeSection : function(section){
if (confirm(this.localize_i18n.multiField.messages.removeConfirmation)){
var sectionsCount = this.getSectionsCount();
if(sectionsCount<=2){
$(this.config.btnRemove,this.$elem).hide();
}
section.slideUp('fast', function () {$(this).detach();});
}
},
/*
* Get sections count
*/
getSectionsCount: function(){
return this.$elem.children(this.config.section).length;
}
};
multiField.defaults = multiField.prototype.defaults;
$.fn.multifield = function(options) {
return this.each(function() {
new multiField(this, options).init();
});
};
})( jQuery, window, document );
$('#projects').multifield({
section: '.group',
btnAdd:'#btnAdd',
btnRemove:'.btnRemove'
});
JS Autocomplete :
$( function() {
var projects = [
{
value: "jquery",
label: "jQuery"
},
{
value: "jquery-ui",
label: "jQuery UI"
},
{
value: "sizzlejs",
label: "Sizzle JS"
}
];
$( ".project-label" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( ".project-label" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( ".project-label" ).val( ui.item.label );
$( ".project-id" ).val( ui.item.value );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
} );
you have 2 probs here:
1.Your code only for one input textfield. if u add more textfields, all value of textfields will have the same value. u need call autocomplete in foreach
2.After u press add input jquery not call autocomplete again(new input doesn't have autocomplete). So you need call it after new input added.
fixed here:
declare global function:
/**
* jQuery Autocomplete
*/
$( function() {
var projects = [
{
value: "jquery",
label: "jQuery"
},
{
value: "jquery-ui",
label: "jQuery UI"
},
{
value: "sizzlejs",
label: "Sizzle JS"
}
];
refreshAuto = function(){
$(".project-label").each(function(idx,ele){
var item = $(ele);
item.autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
item.val( ui.item.label );
return false;
},
select: function( event, ui ) {
item.val( ui.item.label );
item.attr('id',ui.item.value);
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<div>" + item.label + "</div>" )
.appendTo( ul );
};
});
}
refreshAuto(); // call to init once
} );
at "jQuery Multifield plugin" find '// Add section' add the line so:
// Add section
this.$elem.on('click',this.config.btnAdd,function(e){
e.preventDefault();
$this.cloneSection();
refreshAuto(); //call autocomplete new input
});
hope this help !

Make jQuery auto complete results, Links

I'm using jQuery auto-complete, bundled with jquery-ui. Any way, I need to customize this little bit to pop-up links instead of just texts.
I have a multi dimensional PHP array which contains some texts and corresponding id of that text in MYSQL database.
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
So, now I have a multidimensional js array. But I have no idea how to use those values to create links.
The text items in the array should be the text part of the links, and the IDs should be the URL of the links.
This is my existing code. How to customize this to achive my puurpose...
$("#search_query").autocomplete( {
source: javascript_array
});
$(function() {
var projects = [
{
value: "jquery",
label: "jQuery",
desc: "the write less, do more, JavaScript library",
icon: "jquery_32x32.png"
},
{
value: "jquery-ui",
label: "jQuery UI",
desc: "the official user interface library for jQuery",
icon: "jqueryui_32x32.png"
},
{
value: "sizzlejs",
label: "Sizzle JS",
desc: "a pure-JavaScript CSS selector engine",
icon: "sizzlejs_32x32.png"
}
];
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
});
you can use any custom attributes value,labels are must remaining all are as per your requirement(here we are using desc and icon).
Use the _renderItem option:
Method that controls the creation of each option in the widget's menu.
The method must create a new <li> element, append it to the menu, and
return it.
_renderItem: function( ul, item ) {
return $( "<li data-value='"+item.value+"'><a href='#'>"+item.label+"</a></li>" )
.appendTo( ul );
}
1) Remove this:
.autocomplete( "instance" )._renderItem = function( ul, item ) {
return $( "<li>" )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
2) Add it up here instead. Make sure you have a href parameter or most browsers won't knowledge it as a link.
$( "#project" ).autocomplete({
minLength: 0,
source: projects,
focus: function( event, ui ) {
$( "#project" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#project" ).val( ui.item.label );
$( "#project-id" ).val( ui.item.value );
$( "#project-description" ).html( ui.item.desc );
$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
},
_renderItem: function( ul, item ) {
return $( "<li data-value='"+item.value+"'><a href='#'>"+item.label+"</a></li>" )
.appendTo( ul );
}
});

Custom Autocomplete with jquery

I am working on jquery autocomplete custom data and display.I want to display some static dropdown on keypress in textbox.when user select that list item i want to add it to textbox.
the code which i have tested is
$('#uinput').keyup(function() {
var val = $('#uinput').val();
if(val.length>1) { // check length
// handle successful DWR response
//alert(data);
var b=[{value: "jquery-ui",
label: "jQuery UI",}];
$('#uinput').autocomplete({source:b,
select: function( event, ui ) {
$( "#uinput" ).val( ui.item.label+"="+document.getElementById('uinput').value );
return false;
}
}).data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li>" )
.data('item.autocomplete', item)
.append( "<a>" + item.label + "=" + document.getElementById('uinput').value + "</a>" )
.appendTo( ul );
};
} else {
$('#uinput').autocomplete([]); // clean
}
});
For reference what i want to do
custom autocomplete
I'm not exactly sure what you're trying to accomplish but I think I've put together this example that I think might help you
https://jsfiddle.net/mgxnxhs8/5/
here's my javascript
$(function () {
var availableTags = [{
label: "jQuery 1.9.1",
value: "http://code.jquery.com/jquery-1.9.1.js",
}, {
label: "jQuery 2.1.4",
value: "http://code.jquery.com/jquery-2.1.4.js",
}];
$('#uinput').autocomplete({
source: availableTags,
minLength: 0,
select: function (event, ui) {
$('#uoutput').val(ui.item.value);
return false;
}
}).focus(function () {
$(this).autocomplete("search");
});
});
The dropdown opens up when you enter the textbox and displays the "label" key of the tags. On Select(), it sets the value of another textbox to the "value" key of the selected tag.
Let me know if theres something I missed. Hope this helps

jQuery Catcomplete with links

So, I'm trying to use HTML links in my catcomplete results, but jquery automatically transforms my html code into text, like on the image:
And my jQuery code is:
$( "#global-search" ).catcomplete({
delay: 0,
source: "globalsearch.php"
});
Please, dont say to me to use select: function( event, ui ) {
window.location.href = ui.item.value;
}, because it works only once when using ajax (I really don't know why, but it just doesn't work), and I asked some questions here yesterday asking how to fix it, and nobody helped me with it.
So, back with the html transformed into text, how can I add an html hyperlink to my results?
globalsearch.php:
Take a look at the Custom Data and Display example. You will see that they have replaced the _renderItem method with a custom one. You'll need to do the same thing to override how your items are displayed.
$('#global-search').data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "item.autocomplete", item )
.append((item.link) ? "<a href='" + item.link + "'>" + item.label + "</a>" : "<a>" + item.label + "</a>" )
.appendTo( ul );
};
Without seeing the output of your globalsearch.php I can't tell you exactly how to set it up, but basically you'd want to add a link attribute to your returned JSON and if the link exists, print the anchor with the link as its href.
How you handle the selection links vs outside links is left as an exercise to the OP.
From the autocomplete widget documentation
Independent of the variant you use, the label is always treated as
text. If you want the label to be treated as html you can use Scott
González' html extension. The demos all focus on different variations
of the source option - look for one that matches your use case, and
check out the code.
Scott González' html extension is https://github.com/scottgonzalez/jquery-ui-extensions/blob/master/autocomplete/jquery.ui.autocomplete.html.js. I have also posted the code below.
/*
* jQuery UI Autocomplete HTML Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
(function( $ ) {
var proto = $.ui.autocomplete.prototype,
initSource = proto._initSource;
function filter( array, term ) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
return $.grep( array, function(value) {
return matcher.test( $( "<div>" ).html( value.label || value.value || value ).text() );
});
}
$.extend( proto, {
_initSource: function() {
if ( this.options.html && $.isArray(this.options.source) ) {
this.source = function( request, response ) {
response( filter( this.options.source, request.term ) );
};
} else {
initSource.call( this );
}
},
_renderItem: function( ul, item) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( $( "<a></a>" )[ this.options.html ? "html" : "text" ]( item.label ) )
.appendTo( ul );
}
});
})( jQuery );
EDIT try the code below while using the extension
$( "#global-search" ).catcomplete({
delay: 0,
html: true,
source: "globalsearch.php"
});

Cannot set property '_renderItem' of undefined jQuery UI autocomplete with HTML

I'm using the following code to render my jQuery UI autocomplete items as HTML.
The items render correctly in the autocomplete control, but I keep getting this javascript error and can't move past it.
Firefox Could not convert JavaScript argument
Chrome Cannot set property '_renderItem' of undefined
donor.GetFriends(function (response) {
// setup message to friends search autocomplete
all_friends = [];
if (response) {
for (var i = 0; i < response.all.length - 1; i++) {
all_friends.push({
"label":"<img style='padding-top: 5px; width: 46px; height: 46px;' src='/uploads/profile-pictures/" +
response.all[i].image + "'/><br/><strong style='margin-left: 55px; margin-top: -40px; float:left;'>" +
response.all[i].firstname + " " + response.all[i].lastname + "</strong>",
"value":response.all[i].firstname + " " + response.all[i].lastname,
"id":response.all[i].user_id});
}
}
$('#msg-to').autocomplete({
source:all_friends,
select:function (event, ui) {
// set the id of the user to send a message to
mail_message_to_id = ui.item.id;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(item.label))
.appendTo(ul);
};
});
Not sure why it is throwing this error, or what I have to do to get past it...Any help is appreciated.
Since I just joined and can't comment on drcforbin's post above, I guess I have to add my own answer.
drcforbin is correct, although it is really a different problem than the one that the OP had. Anyone coming to this thread now is probably facing this issue due to the new version of jQuery UI just released. Certain naming conventions relating to autocomplete were deprecated in jQuery UI in v1.9 and have been completely removed in v1.10 (see http://jqueryui.com/upgrade-guide/1.10/#autocomplete).
What is confusing, however, is that they only mention the transition from the item.autocomplete data tag to ui-autocomplete-item, but the autocomplete data tag has also been renamed to ui-autocomplete. And it's even more confusing because the demos are still using the old syntax (and thus are broken).
The following is what needs to change in the _renderItem function for jQuery UI 1.10.0 in the Custom Data demo here: http://jqueryui.com/autocomplete/#custom-data
Original code:
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
Fixed code:
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
Note the changes for both autocomplete and item.autocomplete. I've verified that this works in my own projects.
I ran into the same problem...seems in later versions, it has to be .data("ui-autocomplete") instead of .data("autocomplete")
I know I'm late with my answer but if people in the future still don't get
.data( "ui-autocomplete-item", item )
to work then try this insted
$(document).ready(function(){
$('#search-id').autocomplete({
source:"search.php",
minLength:1,
create: function () {
$(this).data('ui-autocomplete')._renderItem = function (ul, item) {
return $('<li>')
.append( "<a>" + item.value + ' | ' + item.label + "</a>" )
.appendTo(ul);
};
}
})
});
It worked for me and I was having problem with the login funktion.. I could not login because it said
Uncaught TypeError: Cannot set property '_renderItem' of undefined
Hope this does help someone :)
/kahin
I'm using jquery 1.10.2 and it work using:
.data( "custom-catcomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
And now, with jQuery-2.0.0, it's the name of your new module, but replacing the "." (dot) by the "-" (dash) :
jQuery.widget ('custom.catcomplete', jQuery.ui.autocomplete, {
'_renderMenu': function (ul, items) {
// some work here
}
});
$this.catcomplete({
// options
}).data('custom-catcomplete')._renderItem = function (ul, item) {}
Posting for the sake of any person who stumbles across this post.
This error will also manifest itself if you don't put the .autocomplete inside the document ready event.
The code below will fail:
<script type="text/javascript">
$('#msg-to').autocomplete({
source:all_friends,
select:function (event, ui) {
// set the id of the user to send a message to
mail_message_to_id = ui.item.id;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(item.label))
.appendTo(ul);
};
</script>
while the code below will work:
<script type="text/javascript">
$(function(){
$('#msg-to').autocomplete({
source:all_friends,
select:function (event, ui) {
// set the id of the user to send a message to
mail_message_to_id = ui.item.id;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").html(item.label))
.appendTo(ul);
};
});
</script>
Depending on the version of jquery ui you're using it will either be "autocomplete" or "ui-autocomplete", I made this update to the combobox plugin to fix the problem (~ln 78-85)
var autoComplete = input.data("ui-autocomplete");
if(typeof(autoComplete) == "undefined")
autoComplete = input.data("autocomplete");
autoComplete._renderItem = function(ul, item) {
...

Categories