Parse XML to UL - javascript

I am trying to use JQuery to parse a sitemap.xml to look like this HTML: http://astuteo.com/slickmap/demo/
After working on it for a few hours I decided I really need some help in the right direction.
the main template it has is this, where each indent is a different directory level:
<ul id="primaryNav" class="col4">
<li id="home">Home</li>
<li>Services
<ul>
<li>Graphic Design</li>
<li>Web Development</li>
<li>Internet Marketing
<ul>
<li>Social Media</li>
<li>Search Optimization</li>
<li>Google AdWords</li>
</ul>
</li>
<li>Copywriting</li>
<li>Photography</li>
</ul>
</li>
</ul>
I am using a google sitemap.xml which looks like this:
http://meyers.ipalaces.org/sitemap_000.xml
<url>
<loc>http://meyers.ipalaces.org/</loc>
<lastmod>2011-02-26T09:32:18Z</lastmod>
<changefreq>hourly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>http://meyers.ipalaces.org/meyers/photos/Explorer</loc>
<lastmod>2011-02-26T09:31:33Z</lastmod>
<changefreq>hourly</changefreq>
<priority>0.2</priority>
</url>
The method I came up with avoids setting everything exactly how it is on the css template, but instead I just focused on getting it to have the correct levels:
What it does is takes the level of a URL goes through each level trying to create the list based on the previous level. So with the example www.example.com/brand/model/product/:
it gets the first [0] element, www.example.com this is level 1 so it checks is there a ul[id=1], if not then run create_ul and append it to #content. Now attach a li to the ul it just made..level 1 is "special" because it has to be created first, thats why I have a lot of if level==1 in the code.
For the next element [1] it gets brand which is level 2. This time it checks
is there a li[id=www.example.com] ul[id=2] if there exist, it will create one and then attach a li to the ul.
This method isn't working out for me at all, it also messes up if say level 8 has the same id and something from level 4. I just need a new idea on how to approach this.
Here is my functions as of now, but im sure I should just scrap most of the code:
function create_ul(level, id, prev_id) {
var ul = $('<ul/>',{
id: level
});
if(level==1) {
$('#content').append(ul);
} else {
$('ul[id='+(level-1)+'] li[id='+prev_id+']').append(ul);
}
}
function create_li(level, id, prev_id){
if (level ==1){
if ($('ul[id='+level+']').length == 0) {
create_ul(level, id, prev_id);
} else if ($('ul[id='+level+'] li[id='+id+']').length > 0) {
return;
}
var li = $('<li/>',{
id: id
});
var a = $('<a/>',{
text: level + " - " + id,
href: "nothing yet"
});
$('ul[id='+level+']').append(li);
return;
}
// If there is no UL for the LI, create it
if ($('li[id='+prev_id+'] ul[id='+level+']').length == 0) {
create_ul(level, id, prev_id);
} else if ($('ul[id='+level+'] li[id='+id+']').length > 0) {
return;
}
var li = $('<li/>',{
id: id
});
var a = $('<a/>',{
text: level + " - " + id,
href: "nothing yet"
});
li.append(a);
$('li[id='+prev_id+'] ul[id='+level+']').append(li);
}
$.ajax({
type: "GET",
url: "/sitemap_000.xml",
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
URLS = new Array(new Array(), new Array(), new Array());
$(xml).find("loc").each(function(){
var url = $(this).text();
URLS[1].push(url);
url = url.replace("http://", "")
var url_array = url.split("/");
URLS[0].push(url_array);
var rawLastMod = $(this).parent().find('lastmod').text();
var timestamp = rawLastMod.replace(/T.+/g, '');
var lastMod = formatDate(timestamp);
URLS[2].push(lastMod);
});
$(URLS[0]).each(function(i, url_array){
$(url_array).each(function(index, fragment){
var level = index+1;
var id = fragment;
if(index!=0) {
var prev_id = URLS[0][i][index-1];
} else {
var prev_id = null;
}
if(id != "") {
create_li(level, id, prev_id);
}
});
});
}
I have decided to reply on a PHP solution instead of Javascript. I am using this PHP script: http://www.freesitemapgenerator.com/xml2html.html

This is my try to it.
Basically it uses an array to store all the urls' pieces.
For example, the url mytest.url.com/sub1/othersub2.html is handled as:
var map = ['mytest.url.com']['sub1']['othersub2.html'];
This is possible because javascript allows you to index arrays using strings.
Full code (just replace your parseXml function and test it on chrome or firefox with firebug):
<script type="text/javascript">
function parseXml(xml) {
//here we will store nested arrays representing the urls
var map = [];
$(xml).find("loc").each(function () {
//some string cleaning due to bad urls provided
//(ending slashes or double slashes)
var url = this.textContent.replace('http://', '').replace('//', ''),
endingInSlash = (url.substr(url.length - 1, 1) == '/'),
cleanedUrl = url.substr(0, url.length - (endingInSlash ? 1 : 0)),
splittedUrl = cleanedUrl.split('/'), //splitting by slash
currentArrayLevel = map; //we start from the base url piece
for (var i = 0; i < splittedUrl.length; i++) {
var tempUrlPart = splittedUrl[i];
//in javascript you can index arrays by string too!
if (currentArrayLevel[tempUrlPart] === undefined) {
currentArrayLevel[tempUrlPart] = [];
}
currentArrayLevel = currentArrayLevel[tempUrlPart];
}
});
var currentUrlPieces = []; //closure to the recursive function
(function recursiveUrlBuilder(urlPiecesToParse) {
//build up a DOM element with the current URL pieces we have available
console.log('http://' + currentUrlPieces.join('/'));
for (var piece in urlPiecesToParse) {
currentUrlPieces.push(piece);
//recursive call passing the current piece
recursiveUrlBuilder(urlPiecesToParse[piece]);
}
//we finished this subdirectory, so we step back by one
//by removing the last element of the array
currentUrlPieces.pop();
})(map);
}
</script>

Related

How to use different blogger post ID in Javascript variable?

I am trying to make every article views having comma separated every 3 digit number. I have found the code for that.
But I have problem to find specific blogger post ID to use for the code to work fine.
Here's the whole code that I am trying to work on.
<--Viewable area /-->
<span class='entry-time'><b:if cond='data:allBylineItems.author and data:allBylineItems.timestamp.label'><span class='on'><data:allBylineItems.timestamp.label/></span></b:if><time class='published' expr:datetime='data:post.date.iso8601'><data:post.date/></time></span><span class='postviews1' style='margin-left:5px; display:display;'><a expr:name='data:post.id'/> <i class='far fa-eye'/> <span id='bacani'><span id='postviews'/></span> Views</span>
<--comma separated every 3 digit /-->
<script>var angka = document.getElementById('bacani').textContent;var reverse = angka.toString().split('').reverse().join(''),ribuan = reverse.match(/\d{1,3}/g);ribuan = ribuan.join(',').split('').reverse().join('');document.getElementById('bacani').innerHTML= ribuan;</script>
<--code for views count /-->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/> <script> $.each($("a[name]"), function(i, e) { var elem = $(e).parent().find("#postviews"); var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name")); blogStats.once("value", function(snapshot) { var data = snapshot.val(); var isnew = false; if(data == null) { data= {}; data.value = 0; data.url = window.location.href; data.id = $(e).attr("name"); isnew = true; } elem.text(data.value); data.value++; if(window.location.pathname!="/") { if(isnew) blogStats.set(data); else blogStats.child("value").set(data.value); } }); });</script>
I want to change:
<span id='bacani'><span id='postviews'/></span>
and
document.getElementById('bacani').textContent;
to have a specific value id which is post id from blogger. The only thing that i found from internet is
<data:post.id>
Is there any other way that i can make it work other than what I am thinking right now? I think I need specific new id to make it work for every article to have comma separated every 3 digit.
I try to use the code but it only work for one time only. I believe to make it work as a whole I need to use different code to read specific unique id base on data:.post.id from blogger post id itself. But i do not sure how to make it work. I am expecting when I know how to use different method which is making new code that find unique id for different article it would work fine.
You can just replace elem.text(data.value) to
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
The full code would be
<!-- code for views count -->
<script src='https://cdn.firebase.com/v0/firebase.js' type='text/javascript'/>
<script>
/*<![CDATA[*/
$.each($("a[name]"), function (i, e) {
var elem = $(e).parent().find("#postviews");
var blogStats = new Firebase("https://sh-v-3da10-default-rtdb.firebaseio.com/" + $(e).attr("name"));
blogStats.once("value", function (snapshot) {
var data = snapshot.val();
var isnew = false;
if (data == null) {
data = {};
data.value = 0;
data.url = window.location.href;
data.id = $(e).attr("name");
isnew = true;
}
// original count
var count = data.value;
// count separated by comma
var separatedCount = count.toString()
.split('').reverse().join('')
.match(/\d{1,3}/g).join(',')
.split('').reverse().join('');
elem.text(separatedCount);
data.value++;
if (window.location.pathname !== "/") {
if (isnew) blogStats.set(data); else blogStats.child("value").set(data.value);
}
});
});
/*]]>*/
</script>

SCRIPT5007: Unable to get property 'toLowerCase' of undefined or null reference

I have a .aspx file working on SharePoint.
We are using IE11, jQuery 2.2.3, jQuery UI 1.11.4, Bootstrap 3.3.6
We had this system for around three years by a third party, which we stopped business. And not able to contact anymore.
It was working fine until a few weeks ago suddenly the page is loading forever and showing this error
SCRIPT5007: Unable to get property 'toLowerCase' of undefined or null reference
Loading page - capture
I have Googled and it seems like the script is waiting for ConfigurationCube.js to load. But since it's not loading, I think it's waiting forever.
/* handles the displaying of all outstanding items requiring approval*/
var TableCreated=0;
var app="";
var teamsArr = [];
var GlobalDivisionsArr = [];
$(document).ready(function(){
//check to see if the Configuration cube Obj Exists and wait until it does
var checkExist = setInterval(function() {
if (sessionStorage["ConfigurationCube"] != null) {
app = JSON.parse(sessionStorage.ConfigurationCube).AppURL;
/**CreateLookupSectionForEmployees("My Winners","Kaizen List","#ViewWinnersTable");**/
//Displayed using the configuration cube.js file
DisplayUserInformation();
popDD("kznSearchCategory",JSON.parse(sessionStorage.ConfigurationCube).ListOfCategories);
IntialPopulationOfApprovedKaizens("","Kaizen List","#kznSearchResultsTable");
//Initialize date range picker
/**$("#kznEditToDate").datepicker();*/
var CubeMin = (JSON.parse(sessionStorage.ConfigurationCube).SubmissionPeriod).split(" ")[0];
clearInterval(checkExist);
}
}, 500);
});
I also tried in IE8, 9, 10, Edge. All not working.
Our company does not allow Chrome or any other browser so we need to get it work in IE..
My current meta tag is like this. Also tried various ways, but did not work.
<meta http-equiv="x-ua-compatible" content="IE=edge; charset=UTF-8">
Does anyone have any similar problems?
Any kind of idea is appreciated..
When clicking on the error, it directs to ConfigutationCube.js
//Tools for other pages
function compareStrings(a, b) {
// Assuming you want case-insensitive comparison
a = a.toLowerCase();
b = b.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
}
Script snip from SearchKaizen.js
function IntialPopulationOfApprovedKaizens(HeadingTitle,ListName,ElementToAppend){
//Get all current data from lists
var GetKaizenPromise = GetList( "Kaizen List",
"Id,Nominated_x0020_person, Status, Kaizen_x0020_Title,Division/Id, Team/Id,Division/Title, Team/Title, Name, Financial_x0020_Year, Kaizen_x0020_Category,Quarter",
"Division/Id, Team/Id,Division/Title, Team/Title",
"Status eq 'Approved'",
app);
$.when(GetKaizenPromise).done(function(KaizenSelectionData){
var EditButton = "";
var Results = KaizenSelectionData.d.results;
//Creates table structure and heading
var DataTableHtml = "";
var SetVotedBackground = "style='background-color:lightgreen;color:white;'";
var DivisionList = [];
var TeamList = [];
var YearList = [];
var DivisionCheck = [];
var TeamCheck = [];
if(Results.length > 0){
for(r=0;Results.length > r;r++){
TableCreated++;
var ResultsName = Results[r].Nominated_x0020_person;
var KaizenTitle = Results[r].Kaizen_x0020_Title;
var ResultsTeam = Results[r].Team.Title;
var ResultsDivision = Results[r].Division.Title;
var ResultsTeamId = Results[r].Team.Id;
var ResultsDivisionId = Results[r].Division.Id;
var ResultsCategory = Results[r].Kaizen_x0020_Category;
var ResultsStatus = Results[r].Status;
var ResultsQuarter = Results[r].Quarter;
var ResultsYear = Results[r].Financial_x0020_Year;
EditButton = "<p style='cursor:pointer;' class='edititem text-light-blue' data-itemid='"+Results[r].Id+"' data-listname='"+ListName+"'><i class='fa fa-edit'></i> View</p>";
DataTableHtml += "<tr>"+
"<td>"+ResultsName+"</td><td>"+ResultsDivision+"</td><td>"+ResultsTeam +"</td>"+
"<td>"+ResultsYear+"</td><td>"+ResultsQuarter+"</td><td>"+KaizenTitle +"</td>"+
"<td>"+ResultsCategory +"</td><td>"+EditButton+"</td>"
"</tr>";
//Create the drop down box info from all the results
if($.inArray(ResultsDivision , DivisionCheck ) == -1){
// Add to departments list
DivisionList.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
DivisionCheck.push(ResultsDivision);
//Keep duplicate of original divisions list
GlobalDivisionsArr.push({"FullName": ResultsDivision,"ID":ResultsDivisionId});
}
if($.inArray(ResultsTeam , TeamCheck) == -1){
// Add to Teams list
TeamList .push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
TeamCheck.push(ResultsTeam);
//Keep duplicates of original list
teamsArr.push({"FullName": ResultsTeam,"ID":ResultsTeamId,"Division":ResultsDivisionId});
}
if($.inArray(ResultsYear , YearList) == -1){
// Add to Year list
YearList.push(ResultsYear );
}
//next Item
}
}else{
//if there are no results
DataTableHtml = "<tr>"+
"<td colspan='8'>No results found</td>" +
"</tr>";
}
YearList.sort();
YearList.reverse();
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
popDD("kznSearchYear",YearList);
popDDSearchWithDataAttr("kznSearchTeam",TeamList,TeamList);
DivisionList.unshift({"FullName": "All","ID":"All"}); //Add All option to division list
popDDVal("kznSearchDivision",DivisionList);
//adds items to DOM
$(ElementToAppend + " tbody").html(DataTableHtml);
//Create column match with returned results
if (Results.length>0){
$.fn.dataTable.ext.errMode = 'console';
$(ElementToAppend).DataTable({
"dom": 'ftipr',
"responsive": true
});
}
$("body").css("overflow","");
//removes overlayer and loading symbol
$("#OverlayFade").addClass("hidden");
$("#Timer").addClass("hidden");
});
}
This snip of the script has popDDVal, and it looks like 'DivisionList' 'TeamList' 'YearList' is returning null. Since this is null it can not break from the loading overlayer.
I was able to narrow it down to this part.
TeamList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
DivisionList.sort(function(a, b) {
return compareStrings(a.FullName, b.FullName);
});
Changed it to this, and it worked. But obviously the sorting is not sorted correctly, but least it works now...
TeamList.sort();
DivisionList.sort();
Instead of passing in an anonymous function pass the function name:
TeamList.sort(compareStrings);
or
DivisionList.sort(compareStrings);

LocalStorage and adding li to list

I'm trying to make a small script that allows for a little notes section. This section would have an input box that allows for adding elements to the list; which will be saved in localStorage so they are not lost when I refresh or close the browser. The code I have is as follows (it's all done through JS even the html, but ignore that.)
var notes = [];
var listthings = "<h2 id=\"titlething\">Notes</h2>" +
"<ul id=\"listing\">" +
"</ul>"
"<input type=\"text\" name=\"item\" id=\"textfield\">" +
"<input type=\"submit\" id=\"submitthing\" value=\"Submit\">";
JSON.parse(localStorage.getItem('notes')) || [].forEach( function (note) {
"<li id=\"listitem\">" + notes + "</li>";
})
$('#submitthing').click(function() {
notes.push($('#textfield').val());
});
localStorage.setItem('notes', JSON.stringify(notes));
Also, how would I go about appending the latest added li between the opening and closing tag? Obviously I'd usually do it using jQuery, but this is puzzling me a little. However, only the 'Notes' loads at the top, any ideas?
Your approach is way off the mark. You don't need JSON at all (this just confuses things) and you don't need to manually create HTML.
Also, you can use an array to store the notes, but since localStorage is the storage area, so an array is redundant. Additionally, without using an array, you don't need JSON. The entire problem becomes much easier to solve.
Unfortunately, the following won't run here in this snippet editor, due to security issues, but it would do what you are asking. This fiddle shows it working: https://jsfiddle.net/Lqjwbn1r/14/
// Upon the page being ready:
window.addEventListener("DOMContentLoaded", function(){
// Get a reference to the empty <ul> element on the page
var list = document.getElementById("notes");
// Loop through localStorage
for (var i = 0; i < localStorage.length; i++){
// Make sure that we only read the notes from local storage
if(localStorage.key(i).indexOf("note") !== -1){
// For each item, create a new <li> element
var item = document.createElement("li");
// Populate the <li> with the contents of the current
// localStorage item's value
item.textContent = localStorage.getItem(localStorage.key(i));
// Append the <li> to the page's <ul>
list.appendChild(item);
}
}
// Get references to the button and input
var btn = document.getElementById("btnSave");
var note = document.getElementById("txtNote");
// Store a note count:
var noteCount = 1;
// When the button is clicked...
btn.addEventListener("click", function(){
// Get the value of the input
var noteVal = note.value;
// As long as the value isn't an empty string...
if(noteVal.trim() !== ""){
// Create the note in localStorage using the
// note counter so that each stored item gets
// a unique key
localStorage.setItem("note" + noteCount, noteVal);
// Create a new <li>
var lstItem = document.createElement("li");
// Set the content of the <li>
lstItem.textContent = noteVal;
// Append the <li> to the <ul>
list.appendChild(lstItem);
// Bump up the note counter
noteCount++;
}
});
});
<input type=text id=txtNote><input type=button value=Save id=btnSave>
<ul id=notes></ul>
This is how I would approach it using jquery. but depens how complex this should be. this is just simple demo.
<input type="text" id="note" />
<button id="add">add note</button>
<ul id="notes"></ul>
javascript and jquery
function addNote(){
var data = localStorage.getItem("notes")
var notes = null;
if(data != null)
{
notes = JSON.parse(data);
}
if(notes == null){
notes = [];
}
notes.push($("#note").val());
localStorage.setItem("notes", JSON.stringify(notes));
refreshNotes();
}
function refreshNotes(){
var notesElement =$("#notes");
notesElement.empty();
var notes = JSON.parse(localStorage.getItem("notes"));
for(var i = 0; i< notes.length; i++){
var note = notes[i];
notesElement.append("<li>"+note+"</li>");
}
}
$(function(){
refreshNotes();
$("#add").click(function(){
addNote();
});
})
example:
http://codepen.io/xszaboj/pen/dOXEey?editors=1010

accessing variable modifications made from within an inline function in javascript

I'm trying to pass local variables to an inline function in javascript and have that (inline) function manipulate those variables, then be able to access the changed variable values in the containing function. Is this even possible? Here's a sample of the code I'm working with:
function addArtists(artist, request, origElm, xml){
//variables
var artistIdArray = [];
/*coding*/
//traverse xml
$('element', xml).each(function(){
/*coding*/
$.ajax({
/*parameters*/
success: function(html) {
var artistAbb = html;
/*coding*/
//add this element's id to the array of ids to make it draggable later
artistIdArray.push(artistAbb);
alert(artistIdArray[artistIdArray.length - 1]);
}//end on success
});//end ajax call
});//end each(function()
alert(artistIdArray.length);
}
The problem is I keep getting artistIdArray.length = 0, even though elements are several elements are 'alerted' after they're added to the array.
Like I said, I don't know if it's even possible without global variables or objects. Any ideas? Am I totally wrong?
Edit: Entire function
function addArtists(artist, request, origElm, xml){
//variables
var artistIdArray = [];
//create ordered list
//set new <ol>s class
var olClass = "artists"; //holds the class of new <ol>
//create id for new <ol>
var olId = "artists"; //holds the id of new <ol>
//create actual <ol> element
var ol = $('<ol></ol>').attr('id',olId)
.addClass(olClass)
.appendTo(origElm);
//create the <li> elements from the returned xml
//create class for new <li>s, (just the request minus the 's')
var liClass = request.substring(0, request.length-1);
//traverse xml
$('element', xml).each(function(){
//create id for new <li> based on artist abbreviation
var artist = $(this).text();
$.ajax({
url: "php/artistToAbb.php",
data: {artist: artist},
dataType: "html",
async: true,
success: function(html) {
var artistAbb = html;
//create li
var li = $('<li></li>').attr('id', artistAbb)
.addClass(liClass)
.appendTo(ol);
//create arrow icon/button for li
var img = $('<img />').attr('id', artistAbb + 'ArrowImg')
.attr("src","images/16-arrow-right.png")
.attr('onclick', "expand(this, '" + artistAbb + "', 'years', 'danwoods')")
.addClass("expImg")
.appendTo(li);
var artistTxt = $('<h2>' + artist + '</h2>')
.addClass("artist_txt")
.attr('onMouseOver', 'catMouseOver(this)')
.attr('onMouseOut', 'catMouseOut(this)')
.appendTo(li);
//tag the ol element's class
$($(origElm)[0]).addClass('expanded');
//add this element's id to the array of ids to make it draggable later
artistIdArray.push(artistAbb);
alert(artistIdArray[artistIdArray.length - 1]);
}//end on success
});//end ajax call
});//end each(function()
//make newly added artist elements draggable
for(var n = 0; n < artistIdArray.length; n++){
//new Draggable(artistIdArray[n], {superghosting: true, detached: true, onEnd: catClearHighlight});
alert(artistIdArray[n]);
}
alert(artistIdArray.length);
}
UPDATED: Now that you've posted your entire code. The answer is that you shouldn't store the elements in the temporary array at all, but create the draggable for each element as the AJAX call returns.
The problem is that while the array is accessible inside the AJAX callback the code at the end of the function (outside the each) executes before the AJAX calls have completed and so the array is empty. If you create each draggable as the call returns, you don't need the intermediate storage variable and the draggable is created as it is inserted into the DOM. The other alternative, would be to make your AJAX calls synchronous {aSync: false}, but this would also potentially tie up the browser until all of the elements have returned. Better, IMO, to live with the asynchronous nature of the AJAX call and handle each element as it is created.
function addArtists(artist, request, origElm, xml){
//create ordered list
//set new <ol>s class
var olClass = "artists"; //holds the class of new <ol>
//create id for new <ol>
var olId = "artists"; //holds the id of new <ol>
//create actual <ol> element
var ol = $('<ol></ol>').attr('id',olId)
.addClass(olClass)
.appendTo(origElm);
//create the <li> elements from the returned xml
//create class for new <li>s, (just the request minus the 's')
var liClass = request.substring(0, request.length-1);
//traverse xml
$('element', xml).each(function(){
//create id for new <li> based on artist abbreviation
var artist = $(this).text();
$.ajax({
url: "php/artistToAbb.php",
data: {artist: artist},
dataType: "html",
async: true,
success: function(html) {
var artistAbb = html;
//create li
var li = $('<li></li>').attr('id', artistAbb)
.addClass(liClass)
.appendTo(ol);
//create arrow icon/button for li
var img = $('<img />').attr('id', artistAbb + 'ArrowImg')
.attr("src","images/16-arrow-right.png")
.attr('onclick', "expand(this, '" + artistAbb + "', 'years', 'danwoods')")
.addClass("expImg")
.appendTo(li);
var artistTxt = $('<h2>' + artist + '</h2>')
.addClass("artist_txt")
.attr('onMouseOver', 'catMouseOver(this)')
.attr('onMouseOut', 'catMouseOut(this)')
.appendTo(li);
//tag the ol element's class
$($(origElm)[0]).addClass('expanded');
new Draggable(artistAbb, {superghosting: true, detached: true, onEnd: catClearHighlight});
}//end on success
});//end ajax call
});//end each(function()
}
You don't need to pass the values at all, just reference them directly in the inline function.
function addArtists(artist, request, origElm, xml){
//variables
var artistIdArray = new Array();
var artistNum = 0;
/*coding*/
//traverse xml
$('element', xml).each(function(){
/*coding*/
//add this element's id to the array of ids to make it draggable later
artistIdArray[artistNum] = "some value";
//alert(artistNum);
artistNum++;
}//end on success
});//end ajax call
});//end each(function()
//test how many elements
for(var n = 0; n < artistIdArray.length; n++)
alert(n);
}
I can't spot the problem, it probably lies somewhere else than in the as far provided (and edited) code.
But as you're already using jQuery, consider assigning them as "global" jQuery property.
var artistIdArray = [];
would then be
$.artistIdArray = [];
and using it would then look like
$.artistIdArray.push(artistAbb);
you could then at end access it the same way
alert($.artistIdArray.length);

What is the best way to cut the file name from 'href' attribute of an 'a' element using jQuery?

For example I've got the simple code:
<ul class="list">
<li>Download file 01</li>
<li>Download file 02</li>
</ul>
and I wish to store in variables only the file names: file01.pdf and file02.pdf, how can I cut them?
Many thanks for the help.
Cheers.
use
lastIndexof and substring
Give anchor tag an id
var elem = document.getElementById ( "anch1" );
elem.href.substring (elem.href.lastIndexOf ( '/' ) + 1 );
Using jQuery
$(function() {
$("ul.list li a").each ( function() {
alert ( $(this).attr ( "href" ).substring ($(this).attr ( "href" ).lastIndexOf ( '/' ) + 1 ) )
});
});
Though you don't have them in this case, in general you would want to strip off the ?search and #hash parts before looking for the last slash to get the file's leafname.
This is very easy using the built-in properties of the link object like pathname instead of processing the complete href:
var a= document.getElementById('link1'); // or however you decide to reference it
var filename= a.pathname.split('/').pop(); // get last segment of path
var fileNames = new Array();
$('.list a').each(function(i, item){
fileNames.push(this.href.substring(this.href.lastIndexOf('/') + 1))
});
This will give you an array of all the filenames, then:
for(var x=0; x<fileNames.length; x++)
{
// Do something with fileNames[x]
}
var myFilename = [];
$("ul.list li a").each(function() {
var href = $(this).attr('href');
var idx = $(this).attr('href').lastIndexOf('/');
myFilename.push((idx >= 0) ? href.substring(idx+1) : href);
});
Here another way:
var arr = [];
$("ul.list li a").each (function(){
arr.push( (this.href.match(/\/[^\/]+$/)[0] || '').substr(1) );
});
var files = $('a[href]').map(function() {
return this.pathname.match(/[^\/]*$/)[0];
});
a[href] will exclude anchors without hrefs (such as named anchors), and pathname will remove query strings and fragments (?query=string and #fragment).
After this, files will contain an array of filenames: ['file01.pdf', 'file02.pdf'].

Categories

Resources