Jquery UI autocomplete select - jquery-ui

I need some help with the code below.
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val.name);
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value);
}
});​
using FireBug, i'm getting this in my console :
jQuery171003666625335785867_1337116004522([{"name":"97300
Cayenne","zzz":"203"},{"name":"97311
Roura","zzz":"201"},{"name":"97312 Saint
Elie","zzz":"388"},{"name":"97320 Saint Laurent du
Maroni","zzz":"391"},{"name":"97351
Matoury","zzz":"52"},{"name":"97354 Remire MontJoly
Cayenne","zzz":"69"},{"name":"97355 Macouria Tonate","zzz":"449"}])
Everything is working very fine, but I don't know how to get the value of 'zzz' on select item.
I tried
alert(ui.item.zzz);
But it doesn't work.

The autocomplete widget expects a data source in array format with either:
Objects containing a label property, a value property, or both
Simple string values
You are currently building up the second (an array of string values), which works fine, but you can also slightly tweak your data as you iterate over it and also supply the other properties in the object:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push({
label: val.name,
zzz: val.zzz
});
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.zzz);
}
});​
Now, since the array you're supplying the widget contains objects with a name property, you should get autocomplete functionality and also gain access to the zzz property.
Here's a working example (without the AJAX call): http://jsfiddle.net/LY42X/

You're source function is only populating the name. If you want everything from that data structure, do this:
$("#auto_cp").autocomplete({
minLength: 3,
//source
source: function(req, add) {
$.getJSON("friends.php?callback=?", req, function(data) {
var suggestions = [];
$.each(data, function(i, val) {
suggestions.push(val); //not val.name
});
add(suggestions);
});
},
//select
select: function(e, ui) {
alert(ui.item.value.zzz);
}
});​

This seems to be an array of objects... what your may be missing is the "[0]" or in general "[index]".
Please check this: jqueryui.com/demos/autocomplete/#event-select

Related

triggering JQuery 'autocomplete' in a secondary textarea

We currently have two HTML textareas 'tinput'(primary) and 'toutput' (secondary) where we mimic the input in the primary to be reflected in the secondary as if someone is really typing in the secondary. The idea is to trigger an 'autocomplete' (over ajax) on the secondary. We have this working but not optimally.
We have attached a JQuery UI 'Autocomplete' (JQAC) to the secondary with a minLength:3 set. You may know that, normally, after 3 characters have been entered, JQAC 'buffers' the char entries thereon after and doesn't make an ajax call for every char that has been entered. Which is ideal.
However, with our secondary mimicking we have subverted this behavior, unfortunately, where after the 3rd char entry a JQAC ajax call is being made for every char after-- which is not optimal. We know why but don't know how to get around it. We believe we've subverted this because we are calling
$('#tinput').autocomplete('search',$('#tinput').val())
in the secondary's key handle, which by JQAC's documentation forces an ajax call.
To summarize, we need the secondary, that has JQAC attached to it, to behave as if someone were really typing into it and the JQAC behaving normally.
Here is JS for what we have as our char input mimic handling(we've changed variable names for this post so please ignore typos):
$("#tinput").on('input', function (e) {
$("#toutput").val($("#tinput").text());
var newEvent = jQuery.Event("keypress");
newEvent.which = e.which; // # Some key code value
$("#toutput").trigger(newEvent);
});
$("#toutput").keypress(function(e) {
$("#toutput").autocomplete('search',$("#toutput").val());
});
$( "#tinput" ).autocomplete({
appendTo: "#modalparent",
source: function( request, response ) {
$.ajax({
url: "https://xxxxxx",
type: "POST",
dataType: "json",
data: JSON.stringify({ "ourterm": request.term}),
success: function( data ) {
response( $.map( data.data.suggestions, function( item ) {
return {
label: item,
value: item
};
}));
}
});
},
minLength: 3,
select: function( event, ui ) {
// console.log( ui.item ?
// "Selected: " + ui.item.label :
// "Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
Any thoughts would be appreciated. Thanks!
We have found an elegant solution. It was a minor modification to our original.
change the trigger event by the primary to 'input' instead of the original 'keypress'.
remove the handler for the secondary.
here is the updated JS:
$("#tinput").on('input', function (e) {
$("#toutput").val($("#tinput").text());
var newEvent = jQuery.Event("input");
newEvent.which = e.which; // # Some key code value
$("#toutput").trigger(newEvent);
});
and delete:
//$("#toutput").keypress(function(e) {
// $("#toutput").autocomplete('search',$("#toutput").val());
// });
DONE.

jQueryUI AutoComplete Remote Source misdirected

I have a jQuery AutoComplete for a text box. The code to initialize the AutoComplete is:
$("#SearchBox1").autocomplete({
autoFocus: false,
source: "Home/AutoComplete",
select: function (event, ui) {
alert(ui.item.label);
}
When the URL doesn't contain a path, the jQuery Autocomplete works, but when the URL contains something like localhost/home/GoToPage/?page=2, then AutoComplete attempts to use /home/GoToPage/Home/AutoComplete. At this point AutoComplete is completely broken, because it is using a bad path.
Are there any good ways of dealing with this problem?
One possible solution is based off of MadRabbit's comments, and Dan Wellman jQueryUI Autocomplete tutorial at http://net.tutsplus.com/tutorials/javascript-ajax/how-to-use-the-jquery-ui-autocomplete-widget/
$("#SearchBox1").autocomplete({
autoFocus: false,
source: function (request, callback) {
//pass request to server
$.getJSON("Home/AutoComplete?term=" + request.term, request, function (responseData) {
//create array for response objects
var suggestions = [];
//process response
$.each(responseData, function (i, val) {
suggestions.push(val);
});
//pass array to callback
callback(suggestions);
});
},
select: function (event, ui) {
$('#SearchBox1').val(ui.item.label);
}
});

autocomplete with amplifyjs

I'm trying to use jqueryui autocmplete with amplifyjs. Thats's to be able to switch between call to real server data and some hardcoded one and for additional flexibility.
For now I do not know how to make jqueryui autocomplete call amplify to refresh itself and perform search. I have the following codesnippet:
amplify.request.define('resId', 'ajax', {
url: 'autocmpleteUrl',
dataType: "json",
type: "POST"
});
$(elementId).autocomplete({
minLength: 1,
source: 'some url',
delay: 0,
focus: function (event, ui) {
$(elementId).val(ui.item.label);
return false;
},
select: function (event, ui) {
$(elementId).val(ui.item.label);
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
I know in autocomplete part it can both be url and json data. But I can't figure out how to make it deal with amplify and make it so that if user inputs text jquery autocomplete requests amplify, not the url itself. Any ideas?
That's close to what you want, but you've forgotten to pass the search term to your request. Your code should be:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request( "resId", request, function( data ) {
response( data );
});
});
});
Which will send the search term as the term query parameter. Since you're doing a direct passthrough of the data, this can also be reduced:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request( "resId", request, response );
});
});
However, in both of these cases you're not handling errors, which means that you can leave the autocomplete in the search state indefinitely. You should use the full amplify.request form to handle errors:
$( elem ).autocomplete({
source: function( request, response ) {
amplify.request({
resourceId: "resId",
data: request,
success: response,
error: function() {
response( [] );
}
});
});
});
I've completed with the following solution:
autocomplete({
source: function(request, response){
amplify.request('resId', function(data){
response(data);
});
},
So you can provide a function to jquery.ui autocomplete and in this function just set the request object and autocomplete data will be filled with data you provide.

jQuery UI Autocomplete how to implement Must Match in existing setup?

I have the following code and am curious as how to force the input to match the contents of the autocomplete:
$("#foo").autocomplete({
source: function( request, response ) {
$.ajax({
url: "index.pl",
dataType: "json",
data: {
type: 'foo',
term: request.term
},
success: function( data ) {
response( $.map( data.items, function( item ) {
return {
value: item.id
}
}));
}
});
},
minLength: 1
});
Answering this question for the benefit of anyone who stumbles upon this problem in 2013(yeah right!)
$("#my_input").autocomplete({
source: '/get_data/',
change: function(event, ui) {
var source = $(this).val();
var temp = $(".ui-autocomplete li").map(function () { return $(this).text()}).get();
var found = $.inArray(source, temp);
if(found < 0) {
$(this).val(''); //this clears out the field if non-existing value in <select><options> is typed.
}
}
});
Explanation:
The map() method creates a jQuery object populated with whatever is returned from the function (in this case, the text content of each <li> element).
The get() method (when passed no argument) converts that jQuery object into an actual Array.
Here is the original link of where I saw the solution.
I hope this helps. Thanks!

How do I pass an extra parameter to Jquery Autocomplete field?

I'm using the JQuery Autocomplete in one of my forms.
The basic form selects products from my database. This works great, but I'd like to further develop so that only products shipped from a certain zipcode are returned. I've got the backend script figured out. I just need to work out the best way to pass the zipcode to this script.
This is how my form looks.
<form>
<select id="zipcode">
<option value="2000">2000</option>
<option value="3000">3000</option>
<option value="4000">4000</option>
</select>
<input type="text" id="product"/>
<input type="submit"/>
</form>
And here is the JQuery code:
$("#product").autocomplete
({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val() +"&",
minLength: 2,
select: function(event, ui){
//action
}
});
This code works to an extent. But only returns the first zipcode value regardless of which value is actually selected. I guess what's happening is that the source URL is primed on page load rather than when the select menu is changed. Is there a way around this? Or is there a better way overall to achieve the result I'm after?
You need to use a different approach for the source call, like this:
$("#product").autocomplete({
source: function(request, response) {
$.getJSON("product_auto_complete.php", { postcode: $('#zipcode').val() },
response);
},
minLength: 2,
select: function(event, ui){
//action
}
});
This format lets you pass whatever the value is when it's run, as opposed to when it's bound.
This is not to complicated men:
$(document).ready(function() {
src = 'http://domain.com/index.php';
// Load the cities straight from the server, passing the country as an extra param
$("#city_id").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term,
country_id : $("#country_id").val()
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
delay: 300
});
});
jQuery("#whatJob").autocomplete(ajaxURL,{
width: 260,
matchContains: true,
selectFirst: false,
minChars: 2,
extraParams: { //to pass extra parameter in ajax file.
"auto_dealer": "yes",
},
});
I believe you are correct in thinking your call to $("#product").autocomplete is firing on page load. Perhaps you can assign an onchange() handler to the select menu:
$("#zipcode").change(resetAutocomplete);
and have it invalidate the #product autocomplete() call and create a new one.
function resetAutocomplete() {
$("#product").autocomplete("destroy");
$("#product").autocomplete({
source:"product_auto_complete.php?postcode=" + $('#zipcode').val(),
minLength: 2,
select: function(event, ui){... }
});
}
You may want your resetAutocomplete() call to be a little smarter -- like checking if the zip code actually differs from the last value -- to save a few server calls.
This work for me. Override the event search:
jQuery('#Distribuidor_provincia_nombre').autocomplete({
'minLength':0,
'search':function(event,ui){
var newUrl="/conf/general/provincias?pais="+$("#Distribuidor_pais_id").val();
$(this).autocomplete("option","source",newUrl)
},
'source':[]
});
Hope this one will help someone:
$("#txt_venuename").autocomplete({
source: function(request, response) {
$.getJSON('<?php echo base_url(); ?>admin/venue/venues_autocomplete',
{
user_id: <?php echo $user_param_id; ?>,
term: request.term
},
response);
},
minLength: 3,
select: function (a, b) {
var selected_venue_id = b.item.v_id;
var selected_venue_name = b.item.label;
$("#h_venueid").val(selected_venue_id);
console.log(selected_venue_id);
}
});
The default 'term' will be replaced by the new parameters list, so you will require to add again.
$('#product').setOptions({
extraParams: {
extra_parameter_name_to_send: function(){
return $("#source_of_extra_parameter_name").val();
}
}
})
$('#txtCropname').autocomplete('Handler/CropSearch.ashx', {
extraParams: {
test: 'new'
}
});

Resources