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
Related
I have a data from my controller and when the page loads I want the autocomplete input to search for that data and select it.
I am able to search the data using:
$( "#autocomplete" ).autocomplete( "search", '<?=$ID?>' );
above code works and showing the correct value of autocomplete. Now I cant select the value so that the autocomplete input triggers change. I wanted the input to trigger change because I will auto populate some input.
The way I select the value pro grammatically is :
select: function( event, ui ) {}
Now i found this:
search: function( event, ui ) {},
Is is possible to combine the two?
How to select searched data from auto complete programmatically ?
Update:
This is how my autcomplete works:
$( ".updatedautocomplete" ).autocomplete({
source:function(request,response){
var $this = $(this);
$.post("url",{
term:request.term
}).done(function(data, status){
response($.map( data, function( item ) {
return {
data
}
return false; // Prevent the widget from inserting the value.
}));
});
},
select: function( event, ui ) {
$( this ).attr( 'data-value' , ui.item.id );
$( this ).attr( 'data-asd' , ui.item.sad );
$( this ).val( ui.item.label );
$( "#modal" ).val( ui.item.qwe.trim() );
$( "#modal" ).val( ui.item.asd.trim() );
$( "#modal" ).val( ui.item.zxc.trim() );
$( "#modal" ).val( ui.item.ert.trim() );
$( "#modal" ).val( ui.item.dfg.trim() );
return false;
}
});
The reason why I wanted select event is to populate some input as shown in the source
You simply do jQuery.val() on the input element, like so.
Edit
Since you seem to want to trigger the selection after an asynchronous data retrieval, you probably want the response event and perform the selection there.
response (event, ui)
Triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data, where a custom source option callback is not required. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled
$(".updatedautocomplete").autocomplete({
source: function(request, response) {
var $this = $(this);
//$.post("url", {
// term: request.term
//})
//.done(function (data, status) {
// response($.map(data, function (item) {
// return {
// data
// }
// return false; // Prevent the widget from inserting the value.
// }));
//
//});
// Simulates some data returned from server
response([
{ label: "Javascript", value: "js" },
{ label: "CSharp", value: "cs" },
{ label: "PHP", value: "php" }
]);
},
response: function(event, ui) {
// Make your preferred selection here
var item = ui.content[0].label;
$(this).val(item).trigger('change');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input class="updatedautocomplete" />
search and select are the events which get triggered when the search is taking place. You don't execute them.
Additionally, I believe the method search (not the event one) is meant rather for "suggesting" users that a value/tag exists in the list and that they need to select it themselves. So, yes, if you need a value programmatically selected (without user interaction) you might need to do it by .val() and optionally .trigger().
I try to make an autocomplete input, as I did sometimes in the past.
But today I have to face a issue i can't really understand.
$( "#search_collab_autocomplete" ).autocomplete({
appendTo :$('.form-add-new-user'),
source : function(requete, response){
$.ajax({
url : $('.form-add-new-user').data('url'),
dataType : 'json',
data : {
email : $('#search_collab_autocomplete').val(),
},
success : function(data){
var arr = [];
var i = 0;
var fullObj = data;
$.each(data, function(index, value){
var obj = {
id: index,
email: value,
};
arr[i] = obj;
i++;
});
response(arr, fullObj);
},
select: function( event, ui ) {
console.log("hi");
}
});
},
minLength: 3
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" ).data("item.autocomplete", item)
.append( "<a>"+item.email + "</a>")
.appendTo( ul );
};
I have this code, which is partially workink because i can see list of result juste below my input field.
But when I click on / when I choose a item with keyboard I can't see nothing happening.. not even a simple console.log('hi');....
Am I using wrong select ?
Your "select" is attached to $.ajax. It must be on the same level as "source" and "minLength".
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 !
I used JqueryUI on this project im working on.
When I focus on the next item in the list with the down arrow key, jqueryui returns the previous selected item
Here's a perfect working sample is here on jsFiddle
Here's the Jquery code
$( "#itemname" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( tags, function( item ){
return matcher.test( item );
}) );
},
//focus: function(event) { alert( event.type ); }
focus : function(event, ui) {
//alert( $(this).val() );
var item_name_this = $(this).val();
$('#properties_item_name').html(item_name_this);
}
});
focus: function (event, ui) {
var item_name_this = ui.item.value;
$('#properties_item_name').html(item_name_this);
}
Demo --> http://jsfiddle.net/VCd4J/16/
This question already has answers here:
JQuery AutoComplete, manually select first searched item and bind click [duplicate]
(2 answers)
Closed 9 years ago.
I am using jquery autocomplete which I am populating from a ruby on rails application and I am creating a custom autcomplete like so:
$.widget( "custom.code_complete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$ul = ul;
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
self._renderItem( ul, item );
});
}
});
$("#r-code").code_complete({
source: "URL",
minLength: 2,
select: function(event, ui) {
$(".button-row").fadeIn();
get_details(ui.item.url);
}
});
I am redirecting a user from another page to the page with the autocomplete form with a parameter in the URL which is a code used for the search, here is the JS to do the search:
function ac_search(code) {
$("#r-code").val(code);
$("#r-code").code_complete('search', code);
}
This performs the search perfectly and displays the drop down list of results. I am trying to have the script then select the first result in the list. I have tried doing it via a selector:
$(".ui-menu-item:first a").click();
This finds the correct element in the autocomplete list but when I try and simulate a click it gives this error:
TypeError: ui.item is null
Is it possible to programmatically click the first item in the autocomplete results list?
Cheers
Eef
$( el ).autocomplete({
autoFocus: true
});
use autoFocus: true
$( el ).autocomplete({
autoFocus: true
...
});