Populate ul in html with JSON data - javascript

Hi im trying to populate ul in html with JSON, i have tried many solutions from this site, but im not having much luck, any suggestions would be gratefully appreciated. Thanks
my code :
<script>
$.getJSON('/simplepie/round/alltables.json', function (data) {
var o = null;
var myArray = new Array();
document.open();
for( var i = 0; i < data.length; i++ )
{
o = data[i];
myArray.push('<li>' + o.title + '</li>');
//document.write(o.source + " <br>" + o.description + "<br>") ;
myArray.push(o.source);
makeUL(o.source);
}
//document.close();
// document.write('Latitude: ' + data.id + '\nLongitude: ' + data.title + '\nCountry: ' + data.description);
function makeUL(array) {
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
});
</script>
</head>
<body>
<ul id="ct"></ul>
</body>
JSON structure
[{"id":"1","source":"Articles | Mail Online",
"time_date":"1422720360",
"title":"Rouhani accuses Iranian hardliners of ",
"description":"DUBAI, Jan 31 (Reuters) - Iranian President Hassan Rouhani",
"link":"http:\/\/www.dailymail.co.uk\/wires\/reuters\/article-2934402\/Rouhani-accuses-Iranian-hardliners-cheering-atom-talks.html?ITO=1490&ns_mchannel=rss&ns_campaign=1490",
"image":"http:\/\/i.dailymail.co.uk\/i\/pix\/m_logo_154x115px.png"}]

Replace your loop with this:
Get a handle on your List since its already in your body <ul id="ct"></ul>:
var ul = document.getElementById("ct");
Then create the li using javascript and append it to your list:
for( var i = 0; i < data.length; i++ )
{
var obj = data[i];
var li = document.createElement("li");
li.appendChild(document.createTextNode(obj.title));
ul.appendChild(li);
}
There is no need for your MakeUL function
Here is a JS Fiddle to help you: http://jsfiddle.net/loanburger/6nrx1zkj/

Thanks to loanburgers solution, i got the code working The o variable needed to be declared.
var ul = document.getElementById("ct");
for( var i = 0; i < data.length; i++ )
{
var o = data[i];
var li = document.createElement("li");
li.appendChild(document.createTextNode(o.title));
ul.appendChild(li);
}
});

Related

Javascript filled unsorted list auto scroll

I'm struggling to make this idea of mine work..
The idea is to auto-scroll the dynamically filled unsorted list.
This is how I've build the Unsorted List with List Items in JavaScript
$.getJSON(sportlink_url + 'programma?gebruiklokaleteamgegevens=NEE&aantaldagen=' + programma_dagen + '&eigenwedstrijden=JA&thuis=JA&uit=JA&' + sportlink_clientID, function (uitslag) {
for (let i = 0; i < Object.keys(uitslag).length; i++) {
//for (let i = 0; i < 1; i++) {
var aanvangstijd = uitslag[i].aanvangstijd;
var thuisteam = uitslag[i].thuisteam;
var uitteam = uitslag[i].uitteam;
var accommodatie = uitslag[i].accommodatie;
var competitiesoort = uitslag[i].competitiesoort;
var datumNumber = uitslag[i].datum.substring(0,2);
var datumMonth = uitslag[i].datum.slice(-4);
var datumMonthClean = datumMonth.substring(0,3);
//Fetch the DIV
var el = document.getElementById("match_program");
//Create new list item
var node = document.createElement("li");
node.setAttribute('role', 'presentation');
//Create ticketDiv
var ticketDiv = document.createElement("div");
ticketDiv.setAttribute('class', 'tg-ticket');
//Create timeBox
var timeBox = document.createElement("time");
timeBox.setAttribute('class', 'tg-matchdate');
timeBox.innerHTML = (datumNumber + " <span>" + datumMonthClean + "</span>");
//Create matchdetail
var matchDetail = document.createElement("div");
matchDetail.setAttribute('class', 'tg-matchdetail');
matchDetail.innerHTML = ("<h4>" + thuisteam + "<span> - </span>" + uitteam + "   |   " + aanvangstijd + ", " + accommodatie);
//Create themeTag
var themeTag = document.createElement("span");
themeTag.setAttribute('class', 'tg-theme-tag');
themeTag.innerHTML = (competitiesoort);
//Build the hole thing
ticketDiv.appendChild(timeBox);
matchDetail.appendChild(themeTag);
ticketDiv.appendChild(matchDetail)
node.appendChild(ticketDiv);
el.appendChild(node);
This is the Unsorted List in HTML
<ul id="match_program" class="tg-tickets tg-tabnav" role="tablist" data-autoscroll="">
</ul>
This is the function i'm currently using for auto-scroll, but it has .ulContent').height() > $('.ulContainer').height() and because my ulContent doesn't have a prefix height in CSS it's not going to work..
And I can't put a height prefix in CSS for the ulContent cause I don't know on forehand if it's going to be 500px of 800px, the unsorted list is being filled from a JSON string.
$(document).ready(function() {
if($('.ulContent').height() > $('.ulContainer').height()) {
setInterval(function () {
start();
}, 3000);
}
});
function animateContent(direction) {
var animationOffset = $('.ulContainer').height() - $('.ulContent').height();
if(direction == 'up') {
animationOffset = 0;
}
}
The animatie function is being called at the bottom of the HTML file just before the closing tags of the body
I manged to figure it out;
var amountGames = Object.keys(uitslag).length
var calulContent = amountGames * 116 + 500;
var setulContent = calulContent + "px";
document.getElementById('ulContent').style.height= setulContent;
That way the ulContent is always filled and the container uses a fixed number of 500px;

Simpler way to print array items into list items (JavaScript)

going through some exercises in a book. Had to print out array items into a list element.
This was the solution supplied by the book.
<!doctype html>
<html lang="en">
<head>
<title>Temperatures</title>
<meta charset="utf-8">
<script>
function showTemps() {
var tempByHour = new Array();
tempByHour[0] = 59.2;
tempByHour[1] = 60.1;
tempByHour[2] = 63;
tempByHour[3] = 65;
tempByHour[4] = 62;
for (var i = 0; i < tempByHour.length; i++) {
var theTemp = tempByHour[i];
var id = "temp" + i;
var li = document.getElementById(id);
if (i == 0) {
li.innerHTML = "The temperature at noon was " + theTemp;
} else {
li.innerHTML = "The temperature at " + [i] + " was " + theTemp;
}
}
}
window.onload = showTemps;
</script>
</head>
<body>
<h1>Temperatures</h1>
<ul>
<li id="temp0"></li>
<li id="temp1"></li>
<li id="temp2"></li>
<li id="temp3"></li>
<li id="temp4"></li>
</ul>
</body>
</html>
I tried going against the book's solution at first and tried to just use a for loop and use the create element method and have the messages print out alongside with them that way but had no luck.
var messageGen = function() {
var forecastByHour = [32, 15, 19, 25, 21];
for (var i =0; i <= forecastByHour.length; i++) {
var temp = forecastByHour[i];
var message = "On the " + [i] + " hour the expected forcase is to be" + temp;
var listItems = document.createElement("li");
listItems.innerHTML = message
}
}
Anybody have a simpler solution to this?
You can use fancy Array manipulation functions like map and join to efficiently construct HTML and manipulate your temperatures. This code is much easier to follow than the posted solution once you understand the higher-level methods behind it (see the linked MDN documentation pages).
function showTemperatures() {
var temperatures = [59.2, 60.1, 63, 65, 62].map(function (t, i) {
return 'The temperature at ' + (i || 'noon') + ' was ' + t
})
document.getElementById('temperatures').innerHTML =
'<li>' + temperatures.join('</li><li>') + '</li>'
}
showTemperatures()
<h1>Temperatures</h1>
<ul id="temperatures"></ul>
This is how I would approach this problem:
Make an array of data.
Create a function to produce an li based on parameters.
Use a for loop to appendChild a li to your target ul element.
var tempByHour = [ 59.2, 60.1, 63, 65, 62 ];
function createLi(temp, i) {
var li = document.createElement("LI");
if (i === 0) {
li.innerText = "The temperature at noon was " + temp;
} else {
li.innerText = "The temperature at " + i + "was " + temp;
}
return li;
}
var i,
len = tempByHour.length,
target = document.getElementById("temps");
for (i = 0; i < len; i++) {
target.appendChild(createLi(tempByHour[i], i));
}
<h1>Temperatures</h1>
<ul id="temps"></ul>
I use for loops instead of maps or forEach loops. If you benchmark the different methods, for loops are ~60% fast than maps & ~80% faster than forEach loops.

search/filter in javascript

Sorry my english is not so good but I hope you will understand my problem.
I made my data base with students names and other details, with all methods, post, get, delete and put. And its all working good. (I am new in programing,begginer, I dont know is it good way to do like I did it).
ime = name // prezime = lastname
var studentiDataStore = {
studenti: [],
postStudent: function(studijId, ime, prezime, brIndexa){
this.studenti.push({
id:this.studenti.length,
studijId: studijId,
ime: ime,
prezime: prezime,
brIndexa: brIndexa
});
return this.studenti[this.studenti.length-1];
},
getStudent: function(id){
if(id){
var targetIndex = -1;
for(var i=0; i<this.studenti.length; i++){
if(this.studenti[i].id===id){
targetIndex = i;
break;
}
}
if(targetIndex>-1){
return this.studenti[targetIndex];
} else {
return null;
}
} else {
return this.studenti;
}
}
},
Now i have this code to draw my students in HTMl
var displayStudents = function(){
var studenti = studentiDataStore.getStudent();
var htmlPresentation = [];
for(var i=0; i<studenti.length; i++){
htmlPresentation.push('<li class="list-group-item">'+ studenti[i].ime + " " + studenti[i].prezime+'</li>');
}
document.getElementById("mainContent").innerHTML = '<ul class="list-group">'+ htmlPresentation.join(" ") + '</ul>'
};
Now i have to make search/filter for my students, i tried to find answer but unsuccessful.
My question is, how to make search filter, when I write first letter(and so on) it show me all names starting with that letter ? Thank you
Add a text input on top of the list
<input type="text" id="searchInput" onkeyup="searchFilter()" placeholder="Search for names..">
then add this function in the script
function searchFilter() {
// Declare variables
var input, filter, ul, li, a, i;
input = document.getElementById('searchInput');
filter = input.value.toUpperCase();
ul = document.getElementsByClassName("list-group")[0];
li = ul.getElementsByTagName('li');
// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
if (li[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
source: https://www.w3schools.com/howto/howto_js_filter_lists.asp
you maybe could get some help from this working example!
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_table
var displayStudents = function(){
var studenti = studentiDataStore.getStudent();
var htmlPresentation = [];
for(var i=0; i<studenti.length; i++){
if((studenti[i].ime+" "+studenti[i].prezime).startsWith("youname"))
htmlPresentation.push('<li class="list-group-item">'+ studenti[i].ime + " " + studenti[i].prezime+'</li>');
}
document.getElementById("mainContent").innerHTML = '<ul class="list-group">'+ htmlPresentation.join(" ") + '</ul>'
};

Add certain values from JSON object to javascript array

Update: I've tried the suggestions in the comments and it's still not working. I really have no idea why. I've consolidated it to a single loop and fixed the syntax errors noted. Here's the code as it looks now:
$(function() {
$("#json-one").change(function() {
var $dropdown = $(this);
$.getJSON("washroutines.json", function(data) {
var vals = [];
var $jsontwo = $("#json-two");
$jsontwo.empty();
for (var i = 0; i < data.length; i++){
if (data[i].make === $dropdown.val()) {
$jsontwo.append("<option value=\"" + data[i].model + "\">" + data[i].model + "</option>");
}
}
});
});
});
Any additional help would be much appreciated!
Original question:
I'm trying to create dependent drop down menus using a json object, and I'm having trouble getting the second menu to populate based on the first. When the first menu changes, the second goes to a bunch of "undefined"s.
$.getJSON("washroutines.json", function(data) {
var vals = [];
for (i = 0; i < data.length; i++){
if (data.make = $dropdown.val()) {
vals.push(data.model);
}
}
var $jsontwo = $("#json-two");
$jsontwo.empty();
for (i = 0; i < vals.length; i++){
$jsontwo.append("<option value\"" + vals[i] + "\">" + vals[i] + "</option>");
}
Please use small words when explaining things to me, I'm new at this!
contents of the JSON:
[{"make":"Maytag","model":"Bravos","prewashCycle":"Whitest Whites"},
{"make":"Maytag","model":"Awesome","prewashCycle":"Awesome Whitest Whites"},
{"make":"Whirlpool","model":"Cabrio","prewashCycle":"Extra Heavy"},
{"make":"Kenmore","model":"Elite","prewashCycle":"Awesome"}]
Try changing your for loop for this
for (var i = 0; i < data.length; i++){
if (data[i].make === $dropdown.val()) {
vals.push(data[i].model);
}
}

I need to put my LI array element into a UL but I cant

HERE IS THE CODE:
I need to do a couple of things but I am pretty new coding :S.
First I need to format the li elements I am loading into the array into a UL. them I need also to create a loop where I can print those 20 array elements repeating them to display 2300 elements. Thanks :)
var _objetsOfArray = new Array();
var darFormato = function (numero){
var numero = document.createElement("li");
var contenido = document.createTextNode(i);
numero.appendChild(contenido);
document.body.insertBefore(numero);
}
for (i = 0; _objetsOfArray.length < 20; i++ ){
_objetsOfArray.push (i);
darFormato(i);
};
This resolved it for you.
http://jsfiddle.net/t4Vec/
var count = 2300;
while (count){
var _objectsOfArray = [],
ul = document.createElement("ul");
for (var i = 0; i < 20; i++){
var item = document.createElement("li");
item.innerText = i;
_objectsOfArray.push(item);
ul.appendChild(_objectsOfArray[i]);
count --;
}
//do something with UL
document.body.appendChild(ul);
}
If you have a precreated list, you could use innerHTML and parse it accordingly.
My sample just prints a ul with 20 Li elements with the text node set to the index of the node
Edit: New Fiddle: http://jsfiddle.net/t4Vec/1/
I use this on a page to generate some dynamic links:
<ul id="list">
</ul>
and here is the script
var myData = [
"item1",
"item2"
]
function createItems()
{
var ul = document.getElementById("list");
for (var i = 0; i < myData.length; i++)
{
var li = document.createElement("li");
var a = document.createElement("a");
a.href = "http://stackoverflow.com/search?tab=newest&pagesize=30&q=" + myData[i].toLowerCase();
a.target = "_blank";
a.innerHTML = myData[i];
li.appendChild(a);
ul.appendChild(li);
}
}
createItems();
where I changed the hrefs to SO :)
I hope taking a look will help you

Categories