What does formatResult and formatItem options do in JQuery Autocomplete? - javascript

Am a bit confused here, what does the formatResult and formatItem do in the JQuery Autocomplete plugin?
I have a function that is returning a comma separated string (from Django), but my autocomplete function is unable to split the string into individual entries/rows, how can i achieve this using autocomplete functions?
e.g the returned result looks like this and this what autocomplete is showing :-
["one","oneTwo", "Onethree", "anotherOne"]
I want when showing in the autocomplete field to have it split like this:-
one
oneTwo
Onethree
anotherOne
I have a feeling i can use the formatResult and formatItem but i dont know how, there are no good examples out there !!
my code in the html template:
function autoFill(){
$("#tags").autocomplete("/taglookup/", {
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300
});
}
Am using Dajango to process the GET request.
Gath

formatItem formats an item for display in the dropdown list, while formatResult formats the item for display in the inputbox once it is selected.
By default, autocomplete expects to get data from the specified url formatted as:
foo|bar|baz|bing
zaz|ding|blop|grok
where each line is a row of data; each row being the data that it passes to formatItem and formatResult. You may want to take the path of least resistance and return data in the way it likes.
If you want to use data that doesn't fit autocomplete's assumptions, you'll need to use the (undocumented, as far as I can tell) parse option to identify a function to parse the results of your ajax request. It appears to me that your django view is returning an array rather than returning a formatted string. To format your array as jquery would like it:
return HttpResponse('|'.join(your_array), mimetype='text/plain')
Here is an example of doing autocomplete using non-standard autocomplete data (JSON):
<script type="text/javascript">
format_item = function (item, position, length){
return item.title;
}
// Handle data from ajax request
prep_data = function(data){
tmp = $.evalJSON(data);
parsed_data = [];
for (i=0; i < tmp.length; i++) {
obj = tmp[i];
// Other internal autocomplete operations expect
// the data to be split into associative arrays of this sort
parsed_data[i] = {
data: obj ,
value: obj.isbn13,
result: obj.title
};
}
return parsed_data
}
$(document).ready(function(){
$("#fop").autocomplete({
url : "{% url book-search %}",
// undocumented
parse: prep_data,
formatItem: format_item,
});
})
</script>

I have not been able to get formatMatch and formatResult to work so far. I am still working on the 'correct' way to use them. However, as a workaround you can use the parse option as follows. Just to be clear, in this example, formatItem and parse are functional while formatResult and formatMatch are not functional.
jQuery(function(){
$('#profile-tabs_addresses_grid_b_a_PostalCode').autocomplete
('http://test.mydomain.com/locality/postalcodes/', {
minChars:1,
delay:400,
cacheLength:100,
matchContains:true,
max:10,
formatItem:function(item, index, total, query){
return item.PostalCode + ': ' + item.Region + ', ' +
item.City + ', ' + item.Country;
},
formatMatch:function(item){
return item.PostalCode;
},
formatResult:function(item){
return item.PostalCode;
},
dataType:'json',
parse:function(data) {
return $.map(data, function(item) {
return {
data: item,
value: item.PostalCode,
result: item.PostalCode
}
});
}});
});
here is the json data that comes back from the data url ( whitespace
added for easier viewing ):
[
{City:"St. Louis", Country:"USA", PostalCode:"63103", ID:3,
Region:"Missouri"},
{City:"St. Louis", Country:"USA", PostalCode:"63109", ID:1,
Region:"Missouri"},
{City:"St. Louis", Country:"USA", PostalCode:"63119", ID:2,
Region:"Missouri"}
]
When I type a 6 in the postal code box, it shows all three options
properly formatted as:
63103: Missouri, St. Louis, USA
63109: Missouri, St. Louis, USA
63119: Missouri, St. Louis, USA
and when I select one the textbox receives just the selected
postal code.

Related

Have JavaScript send returned values to two inputs elements

I am trying to add a section of code (shown below) to have my audio book picker supply an audio file name, as well as displaying the chapter and chapter number.
How can I make my added code send the second set of returned values to the input field with the id='audio', just as it sends return values to the input with the id='chapter-picker'?
var chapterPicker = myApp.picker({
input: '#chapter-picker',
rotateEffect: true,
formatValue: function (picker, values) {
return values[0] + ' ' + values[1];
},
//Start of what I am trying to add
input: '#audio',
rotateEffect: true,
formatValue: function (picker, values) {
return values[0] + values[1] + '.mp3';
}
//End of what I am trying to add
cols: [
{
textAlign: 'left',
values: ['Genesis', 'Exodus', 'Leviticus'],
onChange: function (picker, book) {
if(picker.cols[1].replaceValues){
picker.cols[1].replaceValues(chapters[book]);
}
}
},
{
values: chapters.Genesis,
width: 160,
},
]
});
input: '#chapter-picker' is not being called because you are overwriting the input field with input: '#audio'. A JSON object cannot have two values for the same key.
From reading the docs on F7, the picker does not appear to support modifying two separate fields. What you could do, is some fun thing where you have two HTMLElements with the same ID, one parses out the response from picker one way, and the other the other way. But that's just off the top of my head.
You could also try putting an array into "inputs". But I have no idea if that will work.

Jquery: Autocomplete with label

I am trying to learn website development.
While learning autocomplete feature of jquery, I tried to put in the labels.
function autocomplete (data) {
var data = data.toString();
var availableTags = data.split(',');
var autocompleteData = [];
for (var i = 0; i < availableTags.length; i++){
autocompleteData[i] = {};
autocompleteData[i].label = i.toString();
autocompleteData[i].value = availableTags[i];
}
$("#tags").autocomplete({
source: autocompleteData,
select: function (event, ui) {
printautocomplete(event, ui)
}
});
};
The autocomplete[i].value is a valid string.
autocompleteData[0]
Object {label: 0, value: "Peter"}
However, I do not see any suggestions.
What is wrong with the way I am using the API?
The API says:
"Array: An array can be used for local data. There are two supported formats:
An array of strings: [ "Choice1", "Choice2" ]
OR An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]
The label property is displayed in the suggestion menu. The value will be inserted into the input element when a user selects an item. If just one property is specified, it will be used for both, e.g., if you provide only value properties, the value will also be used as the label. "
Thank you.
$('#sidebarSearch').autocomplete(
{
source: function(query, result)
{
var query = $('#sidebarSearch').val ();
$.ajax(
{
url:"sidebarSearchFetch.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item)
{
return {
label: item.name,
value: item.usrId
};
}));
}
})
},
appendTo: "#sidebar-form"
});
I am skeptical of line 2 in your code (var data = String()data;) I would use: var data = data.toString();
But if you are sure that the autocompleteData elements do indeed have valid strings, then my best guess would be that perhaps you forgot to give the '#tags' id to your html entry field element.
Finally, if this is not it, to troubleshoot, I would try removing the select: option from the object you are passing to autocomplete() in the line that begins: $("#tags").autocomplete(... so that only the source options is passed.
Another thing to check out is when the code is being run. It is possible that a document.ready() function is needed to ensure that that when the autocomplete feature is added to the DOM element with the id '#tags', that the element has already been created.
The autocomplete works fine. Instead of completing "value", it completes "label".
So when I type in "1", it suggests "1", "10", "11", etc.
Autocomplete applying value not label to textbox answers how to change to to by-value.

How to return an object using jQuery, not only the value

I'm looking for a way of replacing .val(); in jQuery with something like .array or .object. So instead of getting only the value of a drop down, i can return the full array for the selected value.
I have a drop down which allows a user to select multiple 'gameTypes', i'm outputting this to the screen and when the user clicks next the content of these 'gameTypes' should be sent as a JSON request.
The code i'm currently using is below however it only returns the 'gametype' name, so when i run the code i get 'RPG' in the console. What i need is the full object, so RPG, publishers, games etc.
Ive looked at the API documentation in jQuery and can't find a way of doing it, is it possible with jQuery?
Js Code:
$("#nextbutton").click(function () {
var datatosend = {
gametypes: [],
market: [] //This is populated using the same method however i don't need the whole object, just the name so this works
};
$("#comboGameType").find(":selected").each(function() {
var str = $(this).val();
datatosend.gametypes.push(str);
console.log(str);
});
});
JSON example:
{
"games": [{
"gameType": "RPG",
"publishers": [{
"publisher": "Square",
"titles": [{
"title": "Final Fantasy",
"gameReleases": [ 2006, 2008, 2010, 2012, 2013, 2014 ]
}]
}]
}]
}
The html is pretty standard, it's populated through js
<select id="comboGameType" class="selectpicker" multiple> </select>
JS to handle changes to drop down and display selections:
$('#comboGameType').change(function () {
var values = $('#comboGameType').val();
var parsedData = JSON.parse($myData);
for (var i = 0; i < values.length; i += 1) {
$('#output').append("<div>" + values[i] + "</div>")
}
});
Heres a fiddle to show as an example - when you view console see the value of the drop down is returned, however i'm trying to return the FULL object (so everything in RPG for example) http://jsfiddle.net/2Ma7U/
You can use jQuery data to store the entire object and retrieve it later.
$(parsedData.genres).each(function (i) {
$("#pubCombo").append($("<option/>", {
val: this.genre,
html: this.genre,
data: this
}));
});
$("#next").click(function () {
var datatosend = {
gametypes: [],
market: []
};
$("#pubCombo").find(":selected").each(function() {
var obj = $(this).data();
datatosend.gametypes.push(obj);
console.log(obj);
});
});
Updated fiddle http://jsfiddle.net/2Ma7U/1/

Issue with using JSON.stringify after using jQuery.map

I am writing a bookmarklet (that will eventually be a plugin) to scrape web pages for list items in jQuery under a specified div. I'm having an issue with using JSON.stringify
The following code allows me to convert each individual item to JSON, but has issues when using join to concatenate each string.
var dMap = $("div").filter($("#<div-id>")).find("li").map(function() {
var iObject = {
id: $(this).data('id'),
text: $(this).text(),
list_name: $(this).closest('div').attr('id')
};
return JSON.stringify(iObject);
});
console.log(dMap);
This second snippet of code creates each object in the array correctly, but the resulting array doesn't log the resulting JSON.
var dMap = $("div").filter($("#,div-id.")).find("li").map(function() {
return {
id: $(this).data('id'),
text: $(this).text(),
list_name: $(this).closest('div').attr('id')
};
});
console.log(dMap);
var json = JSON.stringify(dMap);
console.log(json);
Any ideas?
According to the documentation for .map:
As the return value is a jQuery-wrapped array, it's very common to get() the returned object to work with a basic array.
Have you tried:
var json = JSON.stringify(dMap.get());

Iterating through YQL JSON results in geo.places via javascript

I'm trying to iterate through some JSON results from the YQL geo.places table using the YQL jQuery plugin (http://plugins.jquery.com/project/jquery-yql) troubleshooting with the following code;
$.yql("select * from geo.places where text=#{placename}", {
placename: '90210'
},
function(data) {
var Results = data.query.results;
$.each(Results.place, function(name, value) {
alert(name + ":" + value);
});
});
});
Except, whenever there is more than one "place" in the results, the alert will spit back "0:[object][object]", "1:[object][object]", etc (for each place). Whenever there is only one place result, the alert will spit back all the names and values of just the one place (woeid, name, country, admin1, etc.)
Essentially I'd like to...
input a zip code to YQL
verify the city/state/country from results against user submitted data
update latitude and longitude fields from the results
Thanks!
If Yahoo returns a single place, it does so as a property of results, not as an array of places. If it's not an array, you can't iterate. So test whether it's an array; if it's not, make it one:
$.yql("select * from geo.places where text=#{placename}", {
placename: '90210'
},
function(data) {
var Places = data.query.results.place;
if (!Places.length) Places = [Places];
$.each(Places, function(index, place) {
alert(index + ":" + place.name);
});
});
});

Categories

Resources