JQuery UI catcomplete not returning selected result - html

I am using JQuery UI remote autocomplete with Categories.
$.widget( "custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function( ul, items ) {
var self = this,
currentCategory = "";
$.each( items, function( index, item ) {
if ( item.category != currentCategory ) {
ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
currentCategory = item.category;
}
cat = currentCategory;
self._renderItem( ul, item );
});
}
});
$(function() {
$( "#birds" ).catcomplete({
delay:0,
source: "/search.html?term="+ $("#birds").val(),
minLength: 2,
select: function( event, ui ){
alert(ui.item.value);
}
});
});
The following is the result I get from the source:
[{"value":"Just a Product","id":"1","category":"Category Name"}]
The problem is that I can't get the alert(ui.item.value) to work and display the selected item.
Any help please?
Thanks.

This is not how you deal with the source.
see this.. http://api.jqueryui.com/autocomplete/#option-source
you can use
array
string
callback function
if you want to receive data from a page in json format, use jquery's $.ajax()
see this for ajax http://api.jquery.com/jQuery.ajax/
you can do something like
$.ajax({url: 'search.php?term='+$("#birds").val(),
dataType: 'json',
beforeSend: function(xhrObj){
xhrObj.setRequestHeader("Accept","application/json");
},
async: false,
success: function(data){
bArray=new Array;
bJson=data;
bArray.push(bJson[0].value);
bArray.push(bJson[0].id);
bArray.push(bJson[0].category);// for multiple records put these 3 lines in loop and replace 0 with a counter
}
});
$( "#birds" ).autocomplete({
source: bArray,
select:function(event,ui)
{alert(ui.item.value);}
});
dont forget to declare bArray, bJson
BUT i would still say you are doing it wrong. Instead of using value,id,category together you use use only one of them as autocomplete. can you tell what are you exactly showing in autocomplete

Related

variable insert to a blink function

I'm new to HTML and ajax. I'm trying to insert a ip list from flask , to the ajax and trigger the js function to blink.
but somehow I can't find a way to insert the ip variable (response[i]) into the function value column in a right way.
it is to trigger the blink on the required ip tab in html.
function ajaxForm(){
// var form= new FormData(document.getElementById("myform2"));
var data = {"name":"John Doe"}
$.ajax({
url:"{{ url_for('Submit_form') }}",
type:"post",
contentType:'application/json',
data:JSON.stringify(data),
dataType: "json",
processData:false,
// async: false
success:function(response){
// alert(response)
if (response == "success")
{alert("Success !!!" );}
else {
for(i in response)
{
BLINK(response[i]);
}
}
},
// #time out 也进入 error
error:function(e){
// alert(e.)
alert("Failed submit form trigger!!!!");
}
})
}
<script type="text/javascript">
function BLINK(){
var t = null;
function blink() {
var obj = $('input[id="IP"][value=response[i]]') . <---- here
obj.addClass("blink-class");
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
At first, you shoul always provide the HTML code too :) because now we dont know if the issue is there.
So let's try to solve the problem blindly :)
if i see this correctly, you just go wrong on the element and make it even more complicated than it is since you're using jquery, because if u have an ID on your elem, check this out:
// change this:
var obj = $('input[id="IP"][value=response[i]]') . <---- here // .. is your problem :)
obj.addClass("blink-class");
// with the dot you add this obj, which is it self, on it self :) that cant work :)
// you can try:
var obj = $('input[value="' + response[i] + '"]') // with NO dot and no fixed ID!
obj.addClass("blink-class");
// or try this
var obj = $('#' + response[i]);
obj.addClass("blink-class");
// and put the IP into the ID attraktion of your input element.
Second Problem is you are using an undefined variable "ID":
blink(IP); // in your timeout function
but you didnt declare this var, so if i understand your code right then your response[i] should be the IP?
Your function should look like this:
function BLINK(IP) { // <-- here you need the ip as parameter for your: BLINK(response[i]) from ajax
var t = null;
function blink() {
var obj = $('#' + IP) // and put IP in the id from input
obj.addClass("blink-class")
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
try this, if its doesnt work please provide complete html and your css code too, also we could need an eventually error message from console, you can see that by pressing F12 in FireFox or Chrome and then switch to the console tab, press F5 then to reload the page and see errors, post it too please.
Or try out my jsfiddle for you:
https://jsfiddle.net/AIQIA/tjg659sr/17/
You have to remove dots from your IP and put it as id in your elem you wants get to blink, further you need to remove the dots from the response[i] or in your php code before, easy use $ip = preg_replace('/\./','',$ip);
Or use this to use only the complete IP in your input value, then you dont need to remove dots:
https://jsfiddle.net/AIQIA/tjg659sr/21/
greetz Toxi

Using Spotify webAPI to play random album of artist (ID)

here is my "little" project, as I am not a developer myself please don't blame me for my stupid questions.
I want to create a "audio book machine".
I want to use a Website, that shows several Artists of audiobooks. If I click on one artist, a random audiobook of the clicked artist should be played.
I had a look at this code example: http://jsfiddle.net/qlmhuge/t7a1sh4u/
// find template and compile it
var templateSource = document.getElementById('results-template').innerHTML,
template = Handlebars.compile(templateSource),
resultsPlaceholder = document.getElementById('results'),
playingCssClass = 'playing',
audioObject = null;
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/artists/61qDotnjM0jnY5lkfOP7ve/albums/',
success: function (response) {
callback(response);
}
});
};
var searchAlbums = function (query) {
$.ajax({
url: 'https://api.spotify.com/v1/search',
data: {
q: 'artist:' + query,
type: 'album',
market: "DE"
},
success: function (response) {
resultsPlaceholder.innerHTML = template(response);
}
});
};
results.addEventListener('click', function(e) {
var target = e.target;
if (target !== null && target.classList.contains('cover')) {
if (target.classList.contains(playingCssClass)) {
audioObject.pause();
} else {
if (audioObject) {
audioObject.pause();
}
fetchTracks(target.getAttribute('data-album-id'), function(data) {
audioObject = new Audio(data.tracks.items[0].preview_url);
audioObject.play();
target.classList.add(playingCssClass);
audioObject.addEventListener('ended', function() {
target.classList.remove(playingCssClass);
});
audioObject.addEventListener('pause', function() {
target.classList.remove(playingCssClass);
});
});
}
}
});
searchAlbums('TKKG');
but I cannot figure out how to change it to play a random album by one artist.
The artist will be defindes by the spotify ID so that the artist ist the correct one.
Can someone help me out with my problem? What else info is needed to complete my goal?
I would be very thankful if one can give me a hint, or whatever, to get to the right direction.
Best regards,
goeste
You have to modify your fetchTracks function here:
var fetchTracks = function (albumId, callback) {
$.ajax({
url: 'https://api.spotify.com/v1/albums/' + albumId,
success: function (response) {
callback(response);
}
});
};
jsFiddle link
I got a little closer to the finish line... well, I guess:
I found the following on GitHub:
var SpotifyWebApi = require('spotify-web-api-node');
var spotifyApi = new SpotifyWebApi();
// credentials are optional
// var spotifyApi = new SpotifyWebApi({
// clientId : '',
// clientSecret : '',
// redirectUri : ''
// });
// Get albums by a certain artist
spotifyApi.getArtistAlbums('3meJIgRw7YleJrmbpbJK6S')
.then(function(data) {
console.log('Artist albums', data.body);
}, function(err) {
console.error(err);
});
However, I only get 20 albums out of 35. I need to increase the limit. The max limit is 50, as I read on the developer site of Spotify. As I only need to get one out of the 35 albums (randomly), how can I implement the randomize function and also play function in order to work?
I am still figuring out how to create a link from the results to show on a website with node.js.
Best regards, and thank you in advance for any assistance/help!
-goeste

Why is & turning into & after page load?

I'm using Firefox and working on a page when I notice that & turns into &.
Usually I can fix this by using html_entitiy_decode() - but in this case it's not working.
Then I discovered this. The alert is fired once the page is loaded.
Before
After
The data is loaded using PHP / Yii - not through JS / Ajax. I am however adding / removing brands using JS Knockout.
<ul data-bind="template: { name: 'brand-item-template', data: $root.brands}">
<li>
<span id="<?= $brand->id?>" data-bind="text: brand_name, attr: {'id': brand_id}"><?= $brand->name; ?></span>
</li>
</ul>
Update
I've discovered that this JS Knockout code is what makes the change. But this code should not be triggered until I add a brand. So why is this affecting my &s?
It's the self.addBrand = function() that makes the change. If I remove this function and leave the rest as it is, everything is fine. Can it be a Knockout bug?
$('#store.manage-special-offers').exists(function(){
Store.mangeSpecialOffers();
});
function manageBrandListModel() {
var self = this;
var store_id = $('.data-item-id').val();
var exiting_list = $('.brand-list ul').clone();
// Data
self.brands = ko.observableArray(create_list(exiting_list));
self.brand_name = ko.observable();
self.brand_id = ko.observable();
self.store_id = ko.observable(store_id);
// This is the function that makes the chage
self.addBrand = function() {
if (self.brand_name() != "") {
// Update DB
$('#store.manage-brands').exists(function(){
$.ajax({
url: site_url + '/associatebrand',
type: "POST",
dataType: 'json',
data: {
Brand: {
brandId : self.brand_id(),
storeId : self.store_id(),
add : true
}
},
success: function (data) {
// Add brand to GUI list
self.brands.push(new brand(self.brand_id(), self.brand_name()));
self.brand_name("");
}
});
});
}
}.bind(self);
(...)
function create_list(exiting_list){
var arr_list = [];
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
return arr_list;
}
Can anyone explain why this is happening?
The credit should really go to both JeremyCook and Quentin for pointing me in the right direction.
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
What I did wrong was that I used .html() and the text was returned in HTML format. Changing this to .text() solved my problem.

Can't get the text inside label tags inside jquery-ajax function

I have the following JQuery/AJAX code:
$("button#submit").click(function () {
var form = $('#pick-status-form');
var selectedStatusID = form.find('input[name=statusesList]:checked').val();
//Get the last checked value of the Radio Button
$.ajax({
type: "GET",
url: "updateStatusID.php",
data: { 'refID': lastRefId,
'statusID': selectedStatusID
},
success: function (msg) {
var selectedText = $.trim($('input:radio:checked').parent('label').text());
alert(selectedText);
//Get the text next to the radio button
$("button.btn.btn-default,button.btn.btn-primary").removeClass("disabled");
},
error: function () {
alert("Error");
}
});
});
$("input:radio").removeAttr("checked");
});
The following code:
var selectedText = $.trim($('input:radio:checked').parent('label').text());
alert(selectedText);
Works great in the following function :
$('.statuses-list').change(function () {
var selectedText = $.trim($('input:radio:checked').parent('label').text());
alert(selectedText);
});
But when I put it in the AJAX function it doesn't work (get a null alert).
My question is how can I fix it?
data: {
'refID': lastRefId,
'statusID': selectedStatusID
},
What is lastRefId ? Open your console in browser , I think you will get the js error

jQuery UI Autocomplete - Building custom source

I have json array of the form:
[{"label":<some-label>,"spellings":[<list of spellings>]}, ...]
I need to parse the above array using jquery ui autocomplete. However, there are few constraints:
The autocomplete suggestions should involve matches from "spellings" but should suggest corresponding "label" only. e.g. if there are n "spellings" for a "label" then the autocomplete should show only that particular "label" for n "spellings".
On selecting from the suggestions provided, the corresponding "label" should only be reflected in the text input box.
How should I proceed with it? Any pointers?
And, how to iterate over list of "spellings" for a corresponding "label"?
This is what I'm trying to do, but giving garbled output.
var labels = []
var values = []
$.getJSON($url, function(data) {
$.each(data, function(key, val) {
for (var v in val.value)
values.push(val.value[v])
labels.push(val.label)
});
$("#text1").autocomplete({
minLength: 2,
source: values,
focus: function(event, ui) {
$("#text1").val(ui.item.label);
return false;
},
select: function(event, ui) {
$("#text1").val(ui.item.label);
return false;
}
});
});
I would build up a single source array of items, one for each spelling, where the label property is the label for each spelling and the value property is the spelling itself. This will enable you to quickly filter down results without having to iterate over each object's spelling array and check for matches which could take awhile.
Then, inside a function you define for source, you can do your own filtering logic, only allowing one instance of each "label" in the suggestions list.
Something like this should work (note that the autocomplete is initialized inside of the $.getJSON callback. This is necessary to make sure the source data is loaded before the widget is initialized):
$.getJSON($url, function(data) {
$.each(data, function (i, el) {
source.push({ label: el.label, value: el.label });
$.each(el.spellings, function (j, spelling) {
source.push({ label: el.label, value: spelling });
});
});
/* initialize the autocomplete widget: */
$("input").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i")
, results = [];
/* Make sure each entry is only in the suggestions list once: */
$.each(source, function (i, value) {
if (matcher.test(value.value) && $.inArray(value.label, results) < 0) {
results.push(value.label);
}
});
response(results);
}
});
});
Example: http://jsfiddle.net/MaMZt/