How to create a <ul> based on an array number - javascript

I am trying to make a GitHub profile searcher and what i'm trying to do is:
Get the user Avatar
Get the user Name
Get the user Repositories
I'm having troubles with the last one.
What i can't figure out is how to create a UL based in the user repos quantity.
What i have HTML:
<!DOCTYPE html>
<html>
<head>
<title>Github Profile Searcher</title>
<link rel="stylesheet" href="github-profile.css" />
</head>
<body>
<div id="username-input" class="username-input">
Username:
<input class="username-input-text" type="text" />
</div>
<div id="github-profile" class="github-profile">
<div class="github-profile-avatar">
<span class="github-profile-username">mmckalan</span>
</div>
<div class="github-profile-name">
Alan Mac Cormack
</div>
<div class="github-profile-location">
Napoli,NA
</div>
<div class="github-profile-stats">
<div class="github-profile-stat">
<i class="icon github-icon-repo" /></i>
<span id = "github-profile-repo-count" class="github-profile-repo-count">50</span>
</div>
<div class="github-profile-stat">
<i class="icon github-icon-gist" /></i>
<span class="github-profile-gist-count">12</span>
</div>
</div>
</div>
<script src="github-profile.js"></script>
</body>
JS:
var usernameInput = document.querySelector('#username-input .username-input-text');
var emptyUser = {
login: "",
name: "",
location: "",
public_repos: "",
public_gists: "",
avatar_url: "notfound.png"
};
usernameInput.addEventListener('change', function(event){
var ghReq = new XMLHttpRequest();
ghReq.addEventListener("load", updateProfileBadge);
ghReq.open("GET", "https://api.github.com/users/" + usernameInput.value);
ghReq.send();
});
function updateProfileBadge() {
var response = JSON.parse(this.reponseText);
if (response.message === "Not Found") {
updateDomWithUser(emptyUser);
} else {
updateDomWithUser(response);
}
}
function updateDomWithUser(user) {
var profile = document.getElementById('github-profile');
profile.querySelector('.github-profile-username').innerText = user.login;
profile.querySelector('.github-profile-name').innerText = user.name;
profile.querySelector('.github-profile-location').innerText = user.location;
profile.querySelector('.github-profile-repo-count').innerText =
user.public_repos;
profile.querySelector('.github-profile-gist-count').innerText =
user.public_gists;
profile.querySelector('.github-profile-avatar')
.style.backgroundImage = "url(" + user.avatar_url + ")";
}
updateDomWithUser(emptyUser);
var quantity = document.getElementById('github-profile-repo-count');
var ul = document.createElement("ul");
document.body.appendChild(ul);
What i'm trying to do is something like this:
The quantity of LI is based on the number given by user.public_repos
But it has to fit to the user repos quantity, so i don't know how to solve it.
Could u please give me a hand?

As far as I know, call to "https://api.github.com/users/NAME" would give you only the number of public respos, not names or stars. For that, you need to call "https://api.github.com/users/NAME/repos" - it may be chained after the first call.
Still, creating X list elements without data is quite easy:
var ul = document.createElement("ul");
document.body.appendChild(ul);
for (var i = 0; i < user.public_repos; i++) {
var li = document.createElement("li");
li.textContent = 'example text';
ul.appendChild(li)
}
Or, if you'll get the repos data itself, in form of array:
var ul = document.createElement("ul");
document.body.appendChild(ul);
repos.forEach((repo)=>{
var li = document.createElement("li");
li.textContent = repo.name;
ul.appendChild(li)
})
Another thing - it's better to write
public_repos: 0,
than empty string.

To create a list of repos, you just have to loop through the JSON data returned by /users/{my_user}/repos. In your case, you need two Ajax calls:
The first one gives you information about the user
The second one gives you information about the user repos
Here is a minimal working example with my repositories:
function get(endpoint, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
callback(data);
} else {
console.log(this.status, this.statusText);
}
}
};
req.open('GET', 'https://api.github.com' + endpoint, true);
req.send(null);
}
function handleUser(data) {
var html = '';
html += '<li>' + data.login + '</li>';
html += '<li>' + data.name + '</li>';
document.querySelector('#user > ul').innerHTML = html;
get('/users/Badacadabra/repos', handleUserRepos);
}
function handleUserRepos(data) {
var html = '';
for (var i = 0; i < data.length; i++) {
html += '<li>' + data[i].name + '</li>';
}
document.querySelector('#repos > ul').innerHTML = html;
}
get('/users/Badacadabra', handleUser);
<div id="user">
<ul></ul>
</div>
<hr>
<div id="repos">
<ul></ul>
</div>

Related

Getting information from a JSON and saving in SQL Server using JavaScript

Getting information from a JSON and saving in SQL Server using JavaScript
I have this code, which returns the information I want and shows on the page.
Now I would need to save this information in a SQL Server database, how would that be possible?
This is very difficult for me since I have never worked with API, JSON or JavaScript before
<!DOCTYPE html>
<html>
<head>
<style>
.bodyFrame {
margin: 40px;
}
.headerLabel {
font-weight: bold;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="bodyFrame">
<h2 style="text-align:center;">WIDS JSON Retrieval Example</h2>
<button type="button" onclick="makeServiceCall()">Retrieve JSON Data</button>
<br /><br />
<label class="headerLabel">Programs</label>
<ul id="programUL"></ul>
<div>
<script>
function makeServiceCall() {
var url = "http://widsservicedev.yaharasoftware.com/WidsService/JSON/GetPortagePrograms/?apikey=104043F0-9C24-4957-879D-046868973CC4&callback";
$.getJSON(url, function (data) {
//var myArray = [];
//myArray[0] = data;
parseProgramData(data, url);
});
}
function parseProgramData(jsonData, url) {
$("#dataHeader").empty();
$("#dataHeader").append('<b>' + url + '</b>');
var programUL = document.getElementById("programUL");
for (var pgmIndex = 0; pgmIndex < jsonData.Programs.length; pgmIndex++) {
var pgmLi = document.createElement("li");
var program = jsonData.Programs[pgmIndex];
var programInfoRevision = program.ProgramInfoRevisions[0];
var numberTitle = programInfoRevision.ProgramNumber + " " + programInfoRevision.ProgramTitle;
pgmLi.appendChild(document.createTextNode(numberTitle));
programUL.appendChild(pgmLi);
var linebreak = document.createElement("br");
pgmLi.appendChild(linebreak);
var poLabel = document.createElement("label");
poLabel.appendChild(document.createTextNode("Program Outcomes"));
poLabel.classList.add("headerLabel");
pgmLi.appendChild(poLabel);
var pgmOutcomeUL = document.createElement("UL");
pgmLi.appendChild(pgmOutcomeUL);
for (var poIndex = 0; poIndex < program.ProgramOutcomes.length; poIndex++) {
var poLi = document.createElement("li");
poLi.appendChild(document.createTextNode(program.ProgramOutcomes[poIndex].Description));
pgmOutcomeUL.appendChild(poLi);
}
}
}
</script>
</body>
<footer>
</footer>
</html>

Having trouble with displaying an image through an array

I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>

Dynamic information extraaction

I'm working on a code for extract information from an .json file and print it on a website. I achived all but now I have a problem, the data is showing only 1 result, it create all boxes/places for the other information but only the first "box" have information.
<head>
<!-- Title and Extern files -->
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/db.json"></script>
</head>
<body>
<div id="header">
<h2>SSL Checker</h2>
</div>
<div id="form">
<p>Introduce the URL:</p>
<input id="txtbx" type="text">
<button type="submit" onClick="agregar_caja()">Send</button>
<div id="inf">
<p type="text" id="hl1"></p>
<p type="text" id="hl2"></p>
</div>
<script>
//Extract
console.log(MyJSON[1].url)
var cajas = 2
var boxsaved = MyJSON.length
fnc = function(info) {
hey = document.getElementById("hl1").innerHTML = info.url;
}
//box creator
sm = function agregar_caja() {
document.getElementById("inf").innerHTML += "<p type=text id='hl" + new String(cajas + 1) + "'><br>"
cajas = cajas + 1
}
//Loops
for (i = 0; i < boxsaved; i++) {
sm(MyJSON[i]);
}
for (i = 0; i < MyJSON.length; i++) {
fnc(MyJSON[i]);
}
</script>
</body>
And .json file:
var MyJSON = [{
"url": 'google.es',
},
{
"url": 'yahoo.com',
}]
The problem is that your first box is the only element that your fnc function alters - notice that it only uses the hl1 id to access and alter an element, never hl2+.
I'll try to keep to your original approach, so that you'll follow it more easily. You might do something like this:
var cajas = 2;
function sm(info) {
cajas = cajas + 1;
document.getElementById("inf").innerHTML += (
'<div id="hl' + cajas + '">' + info.url + '</div>'
);
}
for (var i = 0; i < MyJSON.length; i++) {
sm(MyJSON[i]);
}
It is very difficult to read all the code, but as i've got it, you want to add some elements with url's from your JSON.
Ok, we have parent element div with id='inf', lets use javascript function appendChild to add new elements.
And we will use document.createElement('p') to create new elements.
Here is the code, as I've understood expected behavior.
var infContainer = document.getElementById('inf');
var elNumber = 2;
function agregar_caja() {
MyJSON.forEach(function(item,i) {
var newElement = document.createElement('p');
newElement.innerHTML = item.url;
newElement.id = 'hl'+elNumber;
elNumber++;
infContainer.appendChild(newElement);
}
)}

JavaScript - Dynamic To-do list - Editing list

For this To-do list, I am able to add a list. However, once added, I am having issue editing the list that already been added. What I am hoping is when you click Edit, you should able to edit the information and upload the edited information (and making sure the edited information is saved in the local storage when you click Save List to Local Storage). Can someone please help me and go over the JavaScript code and see what I am doing wrong? Below is the HTML, JavaScript and CSS codes:
Here is the Dropbox link if it is easier to download the files: https://www.dropbox.com/sh/qaxygbe95xk4jm1/AADPO98m4416d-ysSGjNt12La?dl=0
<html>
<head>
<title>Dynamic To-do List</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" type="text/css" href="Dynamic To-do List.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript"></script>
<script src="Dynamic To-do List.js" defer="defer"></script>
</head>
<body onload="loadList();">
<h1>To-Do List</h1> Click Button to Add List: Add List
<div id="listFormDiv">
<form id="addListForm">
List name :
<input type="text" id="listNameTxt"><br />
Description : <textarea name="description" id="listDescTxt"></textarea><br />
Date: <input type="text" id="listDateTxt"><br />
Urgent (Yes or No) :
<select id="listUrgentTxt" name="Urgent">
<option value="Yes"> Yes </option>
<option value="No"> No </option>
</select><br />
Category :
<select id="listCategoryTxt" name="category">
<option value="School"> School </option>
<option value="Work"> Work </option>
<option value="Home"> Home </option>
<option value="Others"> Others </option>
</select>
<input type="button" id="addListBtn" value="Add List" onclick="addList()" />
<input type="button" id="updateListBtn" value="Update List" onclick="updateList()" style="visibility: hidden" />
</form>
</div>
<div id="container">
Save List to Local Storage<br />
Clear Local Storage<br />
<div id="listsDiv">
Add To-Do list here<br />
Hide List<br />
Show List<br />
</div>
</div>
</body>
</html>
sortableList();
$(function() {
$("#listDateTxt").datepicker();
});
function loadList() {
console.log(localStorage.getItem("lists"));
var taskList = JSON.parse(localStorage.getItem("lists"));
if (!taskList) {
console.log("There are no tasks saved in the local storage");
} else {
for (var i = 0; i < taskList.length; i++) {
createListDiv(taskList[i]);
}
}
}
//get a reference to the listFormDiv div tag that has the add To-Do List form. list is a global variable that can be access easily from any function
var listFormDiv = getElement("listFormDiv");
var listArray = Array(); //list will hold all the To-do list added through the form
var listIDCount = 0; // list variable will be incremented every time a list is added and will be used to assing a unique ID to every list object.
if (localStorage.getItem("lists")) {
listArray = JSON.parse(localStorage.getItem("lists"));
}
function clearStorage() {
localStorage.clear();
listArray = [];
}
function getElement(id) {
return document.getElementById(id);
}
//function to show the div with the add to-do list form when the add list hyperlink is clicked onLine
function showListDiv() {
//var st = window.getComputedStyle(listFormDiv,null);
console.log(listFormDiv);
listFormDiv.style.display = "block";
}
//list function adds a list when the "add list" button on the form is pressed - 3rd step
function addList() {
var listName = getElement("listNameTxt").value;
var listDesc = getElement("listDescTxt").value;
var listDate = getElement("listDateTxt").value;
var listUrgent = getElement("listUrgentTxt").value;
var listCategory = getElement("listCategoryTxt").value;
//create an instance of the list object with the values from the form
var f;
if (listCategory == "School") {
f = new schoolTask();
f.setValues(listName, listDesc, listDate, listUrgent, listCategory, "blue");
} else if (listCategory == "Work") {
f = new workTask();
f.setValues(listName, listDesc, listDate, listUrgent, listCategory, "red");
}
console.log("school task is " + JSON.stringify(f));
//clear the textboxes in the form
getElement("listNameTxt").value = "";
getElement("listDescTxt").value = "";
getElement("listDateTxt").value = "";
getElement("listUrgentTxt").value = "";
getElement("listCategoryTxt").value = "";
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
console.log(listAddButton);
//listAddButton.style.visibility = "visible";
listEditButton.style.visibility = "hidden";
listFormDiv.style.display = "none";
//add the new list object to the global listArray.
listArray.push(f);
//increment the listID count
listIDCount++;
//add the list to the page and pass in the newly created list object to the createListDiv function
createListDiv(f)
}
// a list object - the second step
function setValues(name, desc, date, urgent, category, color) {
this.name = name;
this.desc = desc;
this.date = date;
this.urgent = urgent;
this.category = category;
this.color = color;
}
function list() {}
//list.prototype.name = "blank name";
list.prototype.name = "blank";
list.prototype.desc = "blank desc";
list.prototype.date = "blank";
list.prototype.urgent = "blank";
list.prototype.category = "blank";
list.prototype.listID = "blank";
list.prototype.color = "blank";
list.prototype.setValues = setValues;
//list.prototype.name = "test";
function schoolTask() {
this.address = "25 Timau Road";
}
inheritFrom(schoolTask, list);
function workTask() {
this.room = "303f";
}
inheritFrom(workTask, list);
function inheritFrom(child, parent) {
child.prototype = Object.create(parent.prototype);
}
//create a div tag to represent the new list and add the new div to the existing place holder div on the page
function createListDiv(list) {
var listDiv = document.createElement("DIV");
listDiv.setAttribute("class", "listClass");
var nameTxt = document.createElement("DIV");
nameTxt.innerHTML = "To-do List Name: " + list.name;
nameTxt.id = "nameTxt" + list.listID;
var lineBreak = document.createElement("BR");
var descTxt = document.createElement("DIV");
descTxt.innerHTML = "Description: " + list.desc;
descTxt.id = "descTxt" + list.listID;
var dateTxt = document.createElement("DIV");
dateTxt.innerHTML = "Date: " + list.date;
dateTxt.id = "dateTxt" + list.listID;
var urgentTxt = document.createElement("DIV");
urgentTxt.innerHTML = "Urgent: " + list.urgent;
urgentTxt.id = "urgentTxt" + list.listID;
var categoryTxt = document.createElement("DIV");
categoryTxt.innerHTML = "Category: " + list.category;
categoryTxt.id = "categoryTxt" + list.listID;
var editLink = document.createElement("A");
editLink.setAttribute("onclick", "editList(" + list.listID + ");"); //Note that we are passing the listID from the list object when calling the editList so we know which list object to fetch to edit when we are editing
editLink.setAttribute("href", "#");
editLink.id = "editLink" + list.listID;
editLink.innerHTML = "Edit";
listDiv.appendChild(nameTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(descTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(dateTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(urgentTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(categoryTxt);
listDiv.appendChild(lineBreak);
listDiv.appendChild(editLink);
getElement("listsDiv").appendChild(listDiv);
}
//global variable to remember which element in the listArray we are editing
var listIndex;
function editList(listID) {
//get the the list object from the array based on the index passed in
var list;
//show the update list button on the html form and hide the add list button on the same form
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
listAddButton.style.visibility = "hidden";
listEditButton.style.visibility = "visible";
//iterate through the listsArray until we find the list object that has the same ID as the id passed in to the function
for (var i = 0; i < listArray.length; i++) {
//if the listID in the list object is the same as the listID passed in to the function then assign the object from the array to the list variable in list function
if (listArray[i].listID == listID) {
//we found the list with the right ID
list = listArray[i];
listIndex = i;
}
}
listFormDiv.style.display = "block";
getElement("listNameTxt").value = list.name;
getElement("listDescTxt").value = list.desc;
getElement("listDateTxt").value = list.date;
getElement("listUrgentTxt").value = list.urgent;
getElement("listCategoryTxt").value = list.category;
//updateList(listIndex);
}
//list function will be called when the update button is pressed on the form
function updateList() {
//save the changed information from the form into the list object in the array based on the array index passed in
listArray[listIndex].name = getElement("listNameTxt").value;
listArray[listIndex].desc = getElement("listDescTxt").value;
listArray[listIndex].date = getElement("listDateTxt").value;
listArray[listIndex].urgent = getElement("listUrgentTxt").value;
listArray[listIndex].category = getElement("listCategoryTxt").value;
var listID = listArray[listIndex].listID; // get the listID from the list object that is in the listsArray at the specificed index;
//now reflect the same changes in the DIV that shows the list
getElement("nameTxt" + listID).innerHTML = "To-do List Name: " + getElement("listNameTxt").value;
getElement("descTxt" + listID).innerHTML = "Description: " + getElement("listDescTxt").value;
getElement("dateTxt" + listID).innerHTML = "Date: " + getElement("listDateTxt").value;
getElement("urgentTxt" + listID).innerHTML = "Urgent: " + getElement("listUrgentTxt").value;
getElement("categoryTxt" + listID).innerHTML = "Category: " + getElement("listCategoryTxt").value;
//reset the listIndex to a value that does not exisit in the array index
listIndex = -1;
var listAddButton = getElement("addListBtn");
var listEditButton = getElement("updateListBtn");
listAddButton.style.visibility = "visible";
listEditButton.style.visibility = "hidden";
//reset form div visibility
listFormDiv.style.display = "none";
getElement("listNameTxt").value = "";
getElement("listDescTxt").value = "";
getElement("listDateTxt").value = "";
getElement("listUrgentTxt").value = "";
getElement("listCategoryTxt").value = "";
}
//Sortable list - http://jqueryui.com/sortable/
function sortableList() {
$("#listsDiv").sortable({
update: function(updateList) {
var sortOrder = getElement(list).sortable('listArray').toString();
console.log(sortOrder);
}
});
}
function saveLists() {
localStorage.setItem("lists", JSON.stringify(listArray));
}
//Hide and Show list
function hideList() {
var listsDiv = getElement("listsDiv");
if (listsDiv.style.display == "block") {
//listsDiv.style.display = "none";
alert("Find a way to hide the list");
}
}
function showList() {
var listsDiv = getElement("listsDiv");
if (listsDiv.style.display == "none") {
listsDiv.style.display = "block";
}
}
#listFormDiv {
border: 1px solid black;
height: 350px;
width: 200px;
position: absolute;
top: 100px;
left: 100px;
padding: 10px;
display: none;
}
#listsDiv { /*Possible #listsDiv*/
height: 350px;
width: 200px;
}
#listDescTxt {
height: 100px;
}
#container {
border: 1px solid black;
height: 650px;
width: 400px;
margin-bottom: 20px;
position: absolute;
top: 100px;
left: 500px;
}
.listClass {
border: 1px solid red;
height: 160px;
width: 200px;
padding: 5px;
}
list.listID is assigned "Blank";
coming from this >
//list.prototype.name = "blank name";
list.prototype.name = "blank";
list.prototype.desc = "blank desc";
list.prototype.date = "blank";
list.prototype.urgent = "blank";
list.prototype.category = "blank";
Line 145: list.prototype.listID = "blank";
list.prototype.color = "blank";
list.prototype.setValues = setValues;
That is why
when it is assigned here >
Line 204: editLink.setAttribute("onclick","editList(" + list.listID + ");");
You click the edit button, it is sending not an *ID but a "blank".
You probably want to reassign the id here >
Line 110: //Assign the id before you push eg. (f.listID == listIDCount++)
//add the new list object to the global listArray.
listArray.push(f);
//increment the listID count
//listIDCount++; why am I incrementing?
//add the list to the page and pass in the newly created list object to the createListDiv function
createListDiv(f)

Sort JSON objects and append to html using javascript/JQM

First time using JSON and total beginner at javascript / JQM
I am trying to read a JSON file, sort it by country name ie title and display in a listview. I am not sure if I am overcomplicating things by trying to use a two dimensional array to sort. Any help, greatly appreciated.
js
<script type="text/javascript">
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open("GET", "european_countries.json", true);
hr.setRequestHeader("Content-type", "application/json", true);
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse (hr.responseText);
var results = document.getElementById("results");
var country, flag, population, avg_growth, date;
for (var obj in data){
var countries = [[]];
var i = 0;
title = data[obj].title;
flag = data[obj].flag;
population = data[obj].population;
avg_growth = data[obj].avg_annual_growth;
date = data[obj].date;
countries[i][0] = title;
countries[i][1] = flag;
countries[i][2] = population;
countries[i][3] = avg_growth;
countries[i][4] = date;
i++;
}
countries.sort();
var listHTML = "";
for (i=0; i < countries.length; i++) {
for (var details in countries[i]) {
listHTML += '<li><a href="#' + countries[i][0] + '</a></li>';
}
}
$("#countryList").empty().append(listHTML).listview("refresh");
}
}
hr.send(null);
// display message while data loading
// could include animated gif or image here
results.innerHTML = "requesting...";
}
</script>
html
<body>
<div id="results"></div>
<div data-role="page" id="home">
<div data-role="header">
<h2>European Countries</h2>
</div>
<div role="main">
<div id="test"></div>
<ul id="countryList" data-role="listview" data-autodividers="true" data-filter="true" data-inset="true">
<li></li>
</ul>
</div>
<div data-role="footer">
</div>
</div><!-- page -->
<script type="text/javascript">
ajax_get_json();
</script>
</body>
json
{
"c1":{
"title":"Russia",
"flag":"flags/flags/Russia.png",
"population":"144,031,000",
"avg_annual_growth":"250,000",
"date":"January 1, 2015"
},
"c2":{
"title":"Germany",
"flag":"flags/Germany.png",
"population":"81,172,000",
"avg_annual_growth":"271,000",
"date":"December 31, 2013"
},
"c3":{
"title":"Turkey",
"flag":"flags/flags/Turkey.png",
"population":"78,214,000",
"avg_annual_growth":"1,035,000",
"date":"December 31, 2014"
}, ...etc
You can convert your JSON object to a single array of country objects
[
{
title:"Russia",
flag:"flags/flags/Russia.png",
population:"144,031,000",
avg_annual_growth:"250,000",
date:"January 1, 2015"
},...
]
Create a sort comparison function that compares the title field of objects in the array (Found HERE):
function compare(a,b) {
if (a.title < b.title)
return -1;
if (a.title > b.title)
return 1;
return 0;
}
So your code would end up something like this:
var countries = [];
for (var obj in data){
countries.push({
title: data[obj].title,
flag: data[obj].flag,
population: data[obj].population,
avg_annual_growth: data[obj].avg_annual_growth,
date: data[obj].date
});
}
countries.sort(compare);
var listHTML = "";
for (var i=0; i < countries.length; i++) {
listHTML += '<li>' + countries[i].title + '</li>';
}
$("#countryList").empty().append(listHTML).listview("refresh");
Working DEMO

Categories

Resources