This is my jquery code to read "test.xml".
var htmldata = 0;
$.get('test.xml', function(data) {
xml_data = $(data);
xml_data.find("order").find("customer").each(function(k, v) {
divClass = inactiveClass;
spanClass = inactiveIcon;
htmldata += '<div class="' + divClass + '"><span class="' + inactiveIcon + '"></span>' + $(this).text() + '</div>';
});
});
alert(htmldata);
In this code I tried to parse test.xml and creating one htmldata. But I am not getting that data out side. If I tried to alert its showing null. How can I take that value outside. Please help me.
function parseXMLdata(data, callback)
{
$.get('test.xml', function(data) {
xml_data = $(data);
xml_data.find("order").find("customer").each(function(k, v) {
divClass = inactiveClass;
spanClass = inactiveIcon;
var htmldata += '<div class="' + divClass + '"><span class="' + inactiveIcon + '"></span>' + $(this).text() + '</div>';
callback(htmldata);
});
});
}
parseXMLdata(data, window.alert);
Related
I have six static html questions and then 3-4 questions being generated by JSON dynamically based upon a form choice made on a page before. What I'm trying to do is generate the questions, then create a progress bar based on the final number of questions created. Where I'm having trouble is using the jQuery when done method after my each loop. It is firing after the first iteration instead of the last. I have tried populating an array "Qs" and passing the array, after reading some other posts, but what I have hasn't worked. I would really like to segment my code and clean it up as much as possible, so I'm trying to stay away from nesting it.
var Qs = [];
var generateQs = function (){
var $dept = sessionStorage.getItem("sFGeneralDepartment1");
var $qWrapper = $("#assessmentTool");
$.getJSON("js/dept-questions.json", function(data) {
var key = $dept;
var vals = [];
switch(key) {
case 'Information technology':
vals = data.IT;
break;
case 'Finance':
vals = data.FIN;
break;
case 'Human resources':
vals = data.HR;
break;
case 'Marketing':
vals = data.MKT;
break;
default:
vals = data.OT;
break;
}
$.each(vals, function(index, value) {
var $cleanID = (value.qID).replace(/q/g, '');
$qWrapper.append('<div class="question-container rangeIcon disabled" id="' + value.qID + '"><p>Question ' + $cleanID +'</p> <h4>' + value.questionText + '</h4><ul class="answer-container"></ul></div>');
$.each(value.answers, function(i, answer) {
var $aID = answer.aID;
var $radioBtn = '<div class="radioBtn"><span class="radioBtnInner"></span></div>';
$('.question-container#' + value.qID + ' .answer-container').append('<li class="survey-item"><div class="icon-holder" id="' + $aID + '"><img src="img/' + answer.iconFileName + '" width="' + answer.iconWidth +'" height="'+ answer.iconHeight + '"/></div><input type="radio" id="'+ $aID + '" value="' + answer.pointValue + '"><label for="' + $aID + '" class="radio" data-popover="'+ answer.popoverText + '">' + $radioBtn + '<span class="labelTopText">' + answer.labelTopText + '<span class="divider">/</span></span><span class="labelBottomText">' + answer.labelBottomText + '</span></label></li>');
});
Qs.push($cleanID);
});
console.log('done');
console.log(Qs);
});
};
$.when(generateQs($,Qs)).done(function() {
//create progress bar
console.log('starting');
var qCount = ($('.question-container').length + 1);
var qList = $('#progressBar');
for (var i = 0; i < qCount; i++){
qList.append('<li class="progress-bar-steps" data-item="q' + (i+1) + '">' + '<span class="step-text">' + (i+1) + '</span>' + '</li>');
$('.question-container').each(function (i, value){
var qId = $(this).attr('id');
if ($(this).hasClass("active")) {
$(this).css('opacity','1.0');
$('#progressBar').find("[data-item='" + qId + "']").addClass('active').html('<span class="step-text">' + (i+1) + '</span>');
$('.progress-bar-steps.active').next('.progress-bar-steps').addClass('next disabled-next').html('<span class="step-text">' + (i+2) + '</span>');
} else {
$(this).addClass('disabled');
}
});
}
});
I'm trying to build viewer that pulls from the twitch API to show which channels are online / offline.
I have 3 buttons: All (displays online and offline results), Online(displays only online results), and Offline (you guessed it...displays only offline results).
My code to display all results is as follows:`
var getAll = function () {
$(".twitch-viewer-information").empty()
twitchUsernames.forEach(function (elem) {
$.when($.getJSON(twitchApi + elem + apiCallback), $.getJSON(twitchStreamApi + elem + apiCallback)).done(function(data1,data2) {
var twitchChannel = elem;
var twitchLogo = data1[0].logo ? data1[0].logo : "https://www.skillsilo.com/images/profile-photo-default-256.png";
var twitchStatus = checkStatus(data2);
var twitchUrl = data1[0].url;
var twitchStreamMessage = data2[0].stream ? data2[0].stream.channel.status.substring(0,33)+"..." : "";
tableRow =$(
'<tr class="twitch-viewer-channel-data" data-href="'+ twitchUrl +'">' +
'<td class="channel-pic"> <img class="channel-image" src="' + twitchLogo + '"</td>' +
'<td class="twitch-viewer-channel-name">' + twitchChannel + '<br> <span class="twitch-stream-message">' + twitchStreamMessage +'</span></td>' +
'<td class="twitch-viewer-channel-status">' + twitchStatus + '</td>' +
'<tr>'
);
$(".twitch-viewer-information").append(tableRow);
tableRow.click(function() {
window.location.href = $(this).data("href");
});
});
});
}
I'd like to now build a function that only returns the channels that are online, using as little code as possible. I have been rewriting the entire function, along with an if statement at the end to accomplish this...but there has got to be a simpler way:
var getOnline = function () {
$(".twitch-viewer-information").empty()
twitchUsernames.forEach(function (elem) {
$.when($.getJSON(twitchApi + elem + apiCallback), $.getJSON(twitchStreamApi + elem + apiCallback)).done(function(data1,data2) {
var twitchChannel = elem;
var twitchLogo = data1[0].logo ? data1[0].logo : "https://www.skillsilo.com/images/profile-photo-default-256.png";
var twitchStatus = checkStatus(data2);
var twitchUrl = data1[0].url;
var twitchStreamMessage = data2[0].stream ? data2[0].stream.channel.status.substring(0,33)+"..." : "";
tableRow =$(
'<tr class="twitch-viewer-channel-data" data-href="'+ twitchUrl +'">' +
'<td class="channel-pic"> <img class="channel-image" src="' + twitchLogo + '"</td>' +
'<td class="twitch-viewer-channel-name">' + twitchChannel + '<br> <span class="twitch-stream-message">' +twitchStreamMessage +'</span></td>' +
'<td class="twitch-viewer-channel-status">' + twitchStatus + '</td>' +
'<tr>'
);
if(twitchStatus === "Online") {
$(".twitch-viewer-information").append(tableRow);
tableRow.click(function() {
window.location.href = $(this).data("href");
});
}
});
});
}
What is the shortest amount of code that I can user to duplicate my getAll function, while allowing me to filter for just the twitchStatus's that are online?
I have some content being added to a page via an AJAX call, and all of my styles are working, except one:
.bld-txt {
font-weight: bold;
}
The call itself looks like this:
$('#quick-search').submit(function(evt) {
evt.preventDefault();
$('.quick-search-info').empty();
var artistName = $(this).serialize();
$.post('/', artistName, function(data) {
var parsedInfo = $.parseJSON(data);
var tourDetails = '';
$.each(parsedInfo, function(i, val) {
tourDetails += '<li class="tour-date">';
tourDetails += '<ul class="show-details">';
tourDetails += '<li class="show-date"><span class="bld-txt">Date: </span>' + parsedInfo[i].formatted_datetime + '</li>';
tourDetails += '<li class="show-venue"><span class="bld-txt">Venue: </span>' + parsedInfo[i].venue.name + '</li>';
tourDetails += '<li class="show-location"><span class="bld-txt">Location: </span>' + parsedInfo[i].venue.city + ", " + parsedInfo[i].venue.region + '</li>';
tourDetails += '<li class="show-tickets"><span class="bld-txt">Tickets: </span>' + parsedInfo[i].ticket_status + '</li>';
tourDetails += '</ul>';
tourDetails += '</li>';
});
$('.quick-search-info').append(tourDetails);
});
});
All other classes that have styles assigned to them thus far are working, but for some reason "bld-txt" will not take effect.
I'm using a reset (normalize.css), but there's nothing in it that should be causing this.
Any guidance is greatly appreciated.
I am new to Javascript and Jquery so please excuse if this is a dumb question
HTML is being constructed dynamically as shown
var favoriteresultag = '<ul>';
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
How can i add/concat one more variable to the class ulseWrap lielement ??
I tried this way
var classactive = '';
if (some condition) {
classactive = 'activeRest';
} else {
classactive = '';
}
favoriteresultag += "<section id='" + name + "' class='ulseWrap lielement '+classactive+' '>" + "<div class='intit someclassss'>" + name + "</div>" + "</section>";
String concatenation, just like you're doing:
favoriteresultag += "<section id='"+name+"' class='ulseWrap lielement " + classactive + "'>" + "<div class='intit someclassss'>"+ name + "</div>" + "</section>";
Try this with jquery if you are using it
$('.actual_class').addClass('new_class')
In your case can be
$('#'+name).addClass('activeRest')
or
$('.ulseWrap.lielement').addClass('activeRest')
Wondering if anyone can help me. I'm trying to put together a weekly photo competition page by pulling in photos from a Flickr gallery, but I can't get the images to display. It works OK for groups, but having some problems with the gallery code. Getting the correct JSON response, but can't get the results to display on the page as good as the group images do.
Here's my Javascript:
$(function() {
var map;
var markers = [];
var infowindow;
// Get gallery photos
var visibleGallery;
$.getJSON("http://api.flickr.com/services/rest/" +
"?method=flickr.galleries.getPhotos" +
"&api_key=XXXX" +
"&photoset_id=XXXX" +
"&extras=geo,tags,url_sq,url_t,url_s,url_m,url_o" +
"&format=json&jsoncallback=?", function(data, textStatus) {
var htmlString = '<div id="weekContainer">';
var weeks = sortIntoWeekArrays(data.photos.photo);
$.each(weeks, function(i, week)
{
var weekNumber = i + 1;
var numberOfWeeks = weeks.length - 1;
htmlString += '<div id="week' + weekNumber + '">';
htmlString += '<ul class="weeks">';
if(i < numberOfWeeks)
{
htmlString += '<li><a class="weekLinksNext" href="#"><span>Next</span></a></li>';
}
var sunday = new Date(week.monday.toUTCString());
sunday.setDate(week.monday.getDate() + 6);
htmlString += '<li class="weekTitle">Week ' + weekNumber + ':</li><li class="weekDate"> ' + week.monday.format("ddd d mmm") + ' — ' + sunday.format("ddd d mmm") + '</li>';
if(i > 0)
{
htmlString += '<li><a class="weekLinksPrev" href="#"><span>Previous</span></a></li>';
}
htmlString += '</ul>';
if(week.winner !== undefined)
{
htmlString += '<p class="galleryTitleFirst">Photo of the Week</p>';
htmlString += '<ul class="imagesWinners">';
htmlString += '<li class="winner"><a href="http://www.flickr.com/photos/' + week.winner.owner + '/' + week.winner.id + '" target="_blank">';
htmlString += '<img title="' + week.winner.title + '" src="' + week.winner.url_m + '" alt="' + week.winner.title + '" />';
htmlString += '</a></li>';
htmlString += '<li class="name">' + week.winner.title + '</li>';
htmlString += '<li class="owner">' + 'by ' + week.winner.ownername + '</li>';
htmlString += '</ul>';
}
htmlString += '<p class="galleryTitle">Our other favourites this week</p>';
htmlString += '<ul class="imagesRunnersUp">';
$.each(week.images, function(i, item)
{
htmlString += '<li><a href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + item.url_sq + '" alt="' + item.title + '" />';
htmlString += '</a></li>';
if(item.longitude == "0" && item.latitude == "0")
{
return true;
}
var latlng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title:item.title
});
marker.content = '<img title="' + item.title + '" src="' + item.url_s + '" alt="' + item.title + '" />';
markers.push(marker);
});
htmlString += '</ul>';
htmlString += '</div>';
});
htmlString += '</div>';
$('div#weekViewer').append(htmlString);
$('div#weekContainer > div').css('float', 'left').css('margin-right', '30px');
$('div#weekContainer').width(weeks.length * 450);
$('div#weekContainer .weekLinksPrev')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '-=450'}, 'slow');
return false;
});
$('div#weekContainer .weekLinksNext')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '+=450'}, 'slow');
return false;
});
});
});
function sortIntoWeekArrays(items)
{
var weeks = [];
// Returns single dimension array containing single dimension arrays
$(items).each(function(i, item)
{
var monday = new Date(item.dateadded * 1000);
monday.setDate(monday.getDate() - monday.getDay() + 1);
monday.setHours(0,0,0,0);
var week, thisWeek;
for (i in weeks)
{
week = weeks[i];
if(week.monday - monday == 0)
{
thisWeek = week;
break;
}
}
if(thisWeek === undefined)
{
thisWeek =
{
monday: monday,
images: []
};
weeks.push(thisWeek);
}
if($.inArray('winner', item.tags.split(" ")) > -1)
{
thisWeek.winner = item;
}
else
{
thisWeek.images.push(item);
}
});
return weeks.sort(function(first, second)
{
return (first.monday > second.monday) - (first.monday < second.monday);
});
}
Any help would be fantastic :)
Regards,
David
Worked it out after some help from a friend. I was missing the date_upload value in the extras argument and item.dateadded needed to change to item.upload.