I am trying to get this code to sort based on the title but display the Title with a hyperlink. So far the code is sorting correctly, but the hyperlinks arent being displayed by the correct Title. It seems to be putting the list links in alphabetical order by the Title, then the subsite links in order by Title.
I want:
First Subsite(www.test.com/firstsubsite)
Google(www.google.com) //<-In list
Last Subsite(www.test.com/lastSubsite)
Yahoo(www.yahoo.com) //<- In list
Currently I am getting:
First Subsite (www.google.com) //<-In list
Google(www.yahoo.com) //<- In list
Last Subsite(www.test.com/firstsubsite)
Yahoo(www.test.com/lastSubsite)
function GetItems() {
var names = [];
var link = [];
$().SPServices({
operation: "GetListItems",
async: true,
listName: "GatheredSites",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='Link_x0020_Url' /></ViewFields>",
completefunc: function(xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var url = $(this).attr("ows_Link_x0020_Url").split(",")[0];
var name = ($(this).attr("ows_Title"));
names.push(name);
link.push(url);
});
$().SPServices({
operation: "GetWebCollection",
webURL: "*url*",
async: true,
completefunc: function(xData, Status) {
$(xData.responseXML).find("Webs > Web").each(function() {
var $node = $(this);
names.push($node.attr("Title"));
link.push($node.attr("Url"));
});
names.sort();
var output = $("#divDisplay");
for (var i = 0, len = names.length; i < len; i++) {
output.append("<li><a href='" + link[i] + "'>" + names[i] + "</li>");
}
}
});
}
});
}
Once you sort the names
array, you have no way to match the corresponding index in the links
array.
You could create an object that has both name and link on each iteration of the xml and push that object into one array.
Then sort the single array of objects by name property
$(xData.responseXML).find("Webs > Web").each(function () {
var $node = $(this);
// single object to store all needed properties from xml
var item = {
name: $node.attr("Title"),
link: $node.attr("Url")
}
// push object to array
names.push(item);
// link.push($node.attr("Url")); - remove links array, no longer needed
});
// sort array by name property
names.sort(function (a, b) {
return a.name > b.name
});
var output = $("#divDisplay");
for (var i = 0, len = names.length; i < len; i++) {
// note properties used for link and name
output.append("<li><a href='" + names[i].link + "'>" + names[i].name + "</li>");
}