How to pull data from a Jsonfile with javascript/jquery - javascript

I´m trying to build a dynamic basket from a JSONfile.
I first started with this file:
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"","phone":"","nbrOrders":0,"name":"","salesPerson":"","customerNo":"","email":""},"order":{"shippingSum":0.0,"orderno":"","voucher":"","currency":"","orderVat":0.0,"orderSum":0.0,"items":[]}}
And with this script I managed to pull info from the different settings and append them to existing html in my basket as you can see in this fiddle:
http://codepen.io/anon/pen/XKKbJL
var nameDiv = document.createElement("td");
nameDiv.id = 'totalIncEx';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#totalIncEx").appendTo("tr.ordersum");
var nameDiv = document.createElement("td");
nameDiv.id = 'vatTotal';
var text3 = document.createTextNode(retailerData.order.orderVat);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#vatTotal").appendTo("tr.ordervat");
var nameDiv = document.createElement("td");
nameDiv.id = 'orderTotal';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#orderTotal").appendTo("tr.ordersumtotal");
Now I have an updated JSON file with data per added product.
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"","phone":"","nbrOrders":0,"name":"","salesPerson":"","customerNo":"","email":""},"order":{"shippingSum":0.0,"orderno":"0","voucher":"","currency":"SEK","orderVat":3322.5,"orderSum":13290.0,"items":[{"qtyAvail":0,"price":6295.0,"qty":1,"artno":"DEL-17812033.10-4","label":"E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard","category":"Computers - Notebooks","manufacturer":"Dell"},{"qtyAvail":31,"price":6995.0,"qty":1,"artno":"20BV001KUK","label":"Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive","category":"Computers - Notebooks","manufacturer":"Lenovo"}]}}
In this field I have info from two different added products. I need to pull data from both of them and have the data separated in their own child element so I can display each product in the basket.
How do I pull for example the price for each product and have that placed in each own child to .carttable in this fiddle?
http://codepen.io/anon/pen/yJJNYZ

var retailerData = {
"del": {
"zip": "",
"city": ""
},
"user": {
"country": "",
"phone": "",
"nbrOrders": 0,
"name": "",
"salesPerson": "",
"customerNo": "",
"email": ""
},
"order": {
"shippingSum": 0.0,
"orderno": "0",
"voucher": "",
"currency": "SEK",
"orderVat": 3322.5,
"orderSum": 13290.0,
"items": [{
"qtyAvail": 0,
"price": 6295.0,
"qty": 1,
"artno": "DEL-17812033.10-4",
"label": "E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard",
"category": "Computers - Notebooks",
"manufacturer": "Dell"
}, {
"qtyAvail": 31,
"price": 6995.0,
"qty": 1,
"artno": "20BV001KUK",
"label": "Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive",
"category": "Computers - Notebooks",
"manufacturer": "Lenovo"
}]
}
}
$.each(retailerData.order.items,function(i,v){//get the item
var div = $('<div/>')
div.append('item '+ '<span>'+ v.artno+'</span>' + '<span>'+ v.price+'</span>' )
$('.carttable').append(div)
})
var nameDiv = document.createElement("td");
nameDiv.id = 'totalIncEx';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#totalIncEx").appendTo("tr.ordersum");
var nameDiv = document.createElement("td");
nameDiv.id = 'vatTotal';
var text3 = document.createTextNode(retailerData.order.orderVat);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#vatTotal").appendTo("tr.ordervat");
var nameDiv = document.createElement("td");
nameDiv.id = 'orderTotal';
var text3 = document.createTextNode(retailerData.order.orderSum);
nameDiv.appendChild(text3)
document.body.appendChild(nameDiv);
$("td#orderTotal").appendTo("tr.ordersumtotal");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="carttable">
</div>
<table class="cartfacts" border="0" cellspacing="0" cellpadding="0">
<tbody>
<tr class="ordersum"><td class="cost costwide">Summa exkl. moms:</td></tr>
<tr class="ordervat"><td class="cost costwide">Moms:</td></tr>
<tr class="ordersumtotal"><td class="cost costwide">Att betala:</td></tr>
</tbody></table>

Its simple.
var retailerData = {"del":{"zip":"","city":""},"user":{"country":"","phone":"","nbrOrders":0,"name":"","salesPerson":"","customerNo":"","email":""},"order":{"shippingSum":0.0,"orderno":"0","voucher":"","currency":"SEK","orderVat":3322.5,"orderSum":13290.0,"items":[{"qtyAvail":0,"price":6295.0,"qty":1,"artno":"DEL-17812033.10-4","label":"E7240/i5-4310U/4GB1/128SSD/12,5HD(1366x768)/W7P 3-Cell/CAM/3YRNBD/W8.1P/US int Keyboard","category":"Computers - Notebooks","manufacturer":"Dell"},{"qtyAvail":31,"price":6995.0,"qty":1,"artno":"20BV001KUK","label":"Lenovo ThinkPad T450 20BV - 14" - Core i3 5010U - 4 GB RAM - 500 GB Hybrid Drive","category":"Computers - Notebooks","manufacturer":"Lenovo"}]}}
$.each(retailerData.order.items,function(key,value){//get the item
document.write(value.artno + " costs " + value.price);
document.write("<br/>");
//or you get each key value in key, value
//so you can easily
document.write("<p>"+value.label+"</p>")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Related

Loading from json into HTML/JavaScript

so I am doing a small project in which I need to put some data about products into a json file, and then load that data into the JavaScript section of the html code. The problem is that I keep getting errors like Microsoft Visual Code is telling me that the object I am trying to load is underfined.
Here is my JSON file:
{
"Data" :
[
{"Name": "Widget", "Price": 25.00, "Quantity": 5 },
{"Name": "Thing", "Price": 15.00, "Quantity": 5 },
{"Name": "Doodad", "Price": 5.00, "Quantity": 10 }
]
}
And here is my code from the HTML page.
<form id="form1">
What product do you wish to search for? <input name="name" type="text" size="20">
</form>
<button onclick="outputprodus()">Submit
</button>
<script type="text/javascript" src="Vlad.json"></script>
<script>
var userdata = JSON.parse(Data);
var produs1_nume = userdata[0].Name;
var produs1_pret = userdata[0].Price;
var produs1_cantitate = userdata[0].Quantity;
function outputprodus(){
var x, y;
x=document.getElementById("form1");
y=x.elements["name"].value;
document.write(y+" este produsul cautat.");
document.write("<br>");
document.write(produs1_nume+" costa "+produs1_pret+" pentru "+produs1_cantitate+" bucati");
}
</script>
Am I loading the data wrong, or making some mistake afterwards?
You were loading json as script.
Here is how to load a file from network.
Codepen: https://codepen.io/kishin-karra/pen/ExVqzRw?editors=1010
var userdata = null;
var produs1_nume = null;
var produs1_pret = null;
var produs1_cantitate = null;
fetch('https://s3.ap-south-1.amazonaws.com/com.instadl.test-assets-123/Vlad.json').then(res => {
res.json().then((data) => {
userdata = data.Data;
produs1_nume = userdata[0].Name;
produs1_pret = userdata[0].Price;
produs1_cantitate = userdata[0].Quantity;
})
})
function outputprodus() {
var x, y;
x = document.getElementById("form1");
y = x.elements["name"].value;
document.write(y + " este produsul cautat.");
document.write("<br>");
document.write(produs1_nume + " costa " + produs1_pret + " pentru " + produs1_cantitate + " bucati");
}

Randomising array from a matrix (bidimensional array)

I Currently have the following matrix
const fileName = [
["a01", "b01", "c01", "d01", "e01", "f01", "g01", "h01", "i01", "j01", "k01", "l01"],
["a02", "b02", "c02", "d02", "e02", "f02", "g02", "h02", "i02", "j02", "k02", "l02"],
["a03", "b03", "c03", "d03", "e03", "f03", "g03", "h03", "i03", "j03", "k03", "l03"],
["a04", "b04", "c04", "d04", "e04", "f04", "g04", "h04", "i04", "j04", "k04", "l04"],
["a05", "b05", "c05", "d05", "e05", "f05", "g05", "h05", "i05", "j05", "k05", "l05"],
["a06", "b06", "c06", "d06", "e06", "f06", "g06", "h06", "i06", "j06", "k06", "l06"],
["a07", "b07", "c07", "d07", "e07", "f07", "g07", "h07", "i07", "j07", "k07", "l07"],
["a08", "b08", "c08", "d08", "e08", "f08", "g08", "h08", "i08", "j08", "k08", "l08"],
["a09", "b09", "c09", "d09", "e09", "f09", "g09", "h09", "i09", "j09", "k09", "l09"],
["a10", "b10", "c10", "d10", "e10", "f10", "g10", "h10", "i10", "j10", "k10", "l10"],
["a11", "b11", "c11", "d11", "e11", "f11", "g11", "h11", "i11", "j11", "k11", "l11"],
["a12", "b12", "c12", "d12", "e12", "f12", "g12", "h12", "i12", "j12", "k12", "l12"]
];
and I create a new array with filenames from it randomising 1 item of each subarray using this function:
function randomise() {
let sequence = fileName.map(option => {
const random = Math.floor(Math.random() * 11);
return option[random];
});
let randomSelection = sequence.map(createURL);
function createURL(fileName) {
return `assets/music/${fileName}.mp3`;
}
console.log(randomSelection);
}
So I get an array such as:
["assets/music/f01.mp3", "assets/music/f02.mp3", "assets/music/b03.mp3", "assets/music/k04.mp3", "assets/music/b05.mp3", "assets/music/f06.mp3", "assets/music/i07.mp3", "assets/music/d08.mp3", "assets/music/d09.mp3", "assets/music/g10.mp3", "assets/music/a11.mp3", "assets/music/d12.mp3"]
But I want to rearrange my matrix in this way:
const fileName = [
["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];
I need to randomly select 1 item from each of the indexes of those subarrays, so one random item ending with "1", another ending with "2", etc
Could you help me please? Thanks!
If these are the actual values of the array you're using, you can just loop from 1 through 12 and stick it together with a random character from the string "abcdefghijk" using randojs' rando() function (or otherwise if you prefer).
for(var i = 1; i <= 12; i++){
console.log("assets/music/" + rando("abcdefghijk") + (i < 10 ? "0" : "") + i + ".mp3")
}
<script src="https://randojs.com/1.0.0.js"></script>
This code uses randojs.com to simplify the randomness and make it easier to read, so if you want to use this code, make sure this is in the head tag of your html document:
<script src="https://randojs.com/1.0.0.js"></script>
To answer the second part of your question (which you posted as another answer to this question), you don't need to keep your fileName variable to construct the HTML here if you'd rather not. You can do it like this instead:
var letters = "abcdefghijk";
for(var i = 0; i < letters.length; i++){
var musicRowID = letters.charAt(i) + "01";
$("#music-grid").append(`<div id="music-row-${musicRowID}" class="row no-gutters"></div>`);
for(var j = 1; j <= 12; j++){
var columnID = letters.charAt(i) + (j < 10 ? "0" : "") + j;
$(`#music-row-${musicRowID}`).append(`<div class="col-1"><button id="${columnID}" class="btn bar song">${columnID.toUpperCase()}</button></div>`);
}
}
Very beautiful Aaron! I created the array like this:
let randomSelection = new Array();
function randomise() {
for (let i = 1; i <= 12; i++) {
let index = `assets/music/${rando("abcdefghijkl")}${i < 10 ? "0" : ""}${i}.mp3`;
randomSelection.push(index);
}
}
randomise()
The only problem now is that I was using the code below to populate a grid based in my fileName variable...
fileName.forEach(row => {
$("#music-grid").append(`<div id="music-row-${row.slice(0, 1)}" class="row no-gutters"></div>`);
row.forEach(col => {
$(`#music-row-${row.slice(0, 1)}`).append(
`<div class="col-1"><button id="${col}" class="btn bar song">${col.toUpperCase()}</button></div>`
);
});
});
Do you reckon it is better to keep my original fileName variable in order to allow it to populate the grid?
Thanks so much!
If I understood you correctly this will give you your desired output. Picking one letter for each number. Hope this helps for whatever you need it.
const fileName = [
["a01", "a02", "a03", "a04", "a05", "a06", "a07", "a08", "a09", "a10", "a11", "a12"],
["b01", "b02", "b03", "b04", "b05", "b06", "b07", "b08", "b09", "b10", "b11", "b12"],
["c01", "c02", "c03", "c04", "c05", "c06", "c07", "c08", "c09", "c10", "c11", "c12"],
["d01", "d02", "d03", "d04", "d05", "d06", "d07", "d08", "d09", "d10", "d11", "d12"],
["e01", "e02", "e03", "e04", "e05", "e06", "e07", "e08", "e09", "e10", "e11", "e12"],
["f01", "f02", "f03", "f04", "f05", "f06", "f07", "f08", "f09", "f10", "f11", "f12"],
["g01", "g02", "g03", "g04", "g05", "g06", "g07", "g08", "g09", "g10", "g11", "g12"],
["h01", "h02", "h03", "h04", "h05", "h06", "h07", "h08", "h09", "h10", "h11", "h12"],
["i01", "i02", "i03", "i04", "i05", "i06", "i07", "i08", "i09", "i10", "i11", "i12"],
["j01", "j02", "j03", "j04", "j05", "j06", "j07", "j08", "j09", "j10", "j11", "j12"],
["k01", "k02", "k03", "k04", "k05", "k06", "k07", "k08", "k09", "k10", "k11", "k12"]
];
let pickedValues = [];
for (i = 0; i <= fileName.length; i++) {
let index = Math.floor(Math.random() * ((fileName.length - 1) - 0 + 1));
pickedValues[i] = (fileName[index][i]);
}
console.log(pickedValues);

How to make Excel file that has been converted to JSON load to table (DataTables) automatically

so i got this assigment, i need to load CSV file into html page,
after i loaded it, i need to make a code that run automatically -
getting the object field name - put it in the table head, and the match the value to each of the object field name.
everything neeed to be automtically (because our teacher is going to check just by adding the csv file - nothing can be hard coded.
we also need to use library called Data Tables.
i managed to do some of the assigment, but most of it is hard coded so it is not good.
here is my html -
<table id="table_id" class="display">
<thead>
<tr id="FieldNames">
</tr>
</thead>
<tbody id="Values">
</tbody>
</table>
and to thid table i added this code -
(with hard coded JSON just to see if i can do it before i import CSV file)
const Json =
[
{
"name": "john",
"age": 35,
"email": "AF#asdsa.com",
"address": "Rishon LeZion"
},
{
"name": "hezi",
"age": 31,
"email": "wertwree#grf.com",
"address": "Rishon LeZion"
},
{
"name": "david",
"age": 23,
"email": "wertewrt#fd.com",
"address": "Rishon LeZion"
},
{
"name": "jacky",
"age": 41,
"email": "wertr#aa.com",
"address": "Rishon LeZion"
}];
$(document).ready(function () {
var Obj = Json[0];
var KeyNames = Object.keys(Obj)
for (let i = 0; i < KeyNames.length; i++) {
var Head = $(`<th>${KeyNames[i]}</th>`);
$("#FieldNames").append(Head);
}
for (let j = 0; j < Json.length; j++) {
var firstVal = Json[j].name
var secondVal = Json[j].age
var thirdVal = Json[j].email
var fourthVal = Json[j].address
var Data = `
<tr class="middle">
<td>${firstVal}</td>
<td>${secondVal}</td>
<td>${thirdVal}</td>
<td>${fourthVal}</td>
</tr>
`;
$("#Values").append(Data);
}
$('#table_id').DataTable();
});
even though the result is good, it is not what i asked to do.
im trying to figure out ways to make it run automatically but it's not working so well for me..
Alright, I did it a while ago, here's the solution:
I separated my logic into two sections:
1) Create headers:
Loop through the children Objects (as in the Objects in the array) and then get their keys with Object.keys()
The keys are your headers. Then throw them in a row inside thead and voila, your headers
2) Create the fields. This is a bit more complicated.
Loop through the main objects and that will give you the objects one by one as the loop unfolds. Then, create a row for each index. Get the values of each object, and make sure you throw them in the correct row as a td by doing something like I did id='object-" + childIndex + "'. Then grab that specific row, and after you get Object.values() from your object, throw them one by one with a loop inside of the row. TA DA
P.S. Don't ask me why I used jquery. I used it because I'm not a masochist to do this with pure JS
const json = [{
"name": "john",
"age": 35,
"email": "AF#asdsa.com",
"address": "Rishon LeZion"
},
{
"name": "hezi",
"age": 31,
"email": "wertwree#grf.com",
"address": "Rishon LeZion"
},
{
"name": "david",
"age": 23,
"email": "wertewrt#fd.com",
"address": "Rishon LeZion"
},
{
"name": "jacky",
"age": 41,
"email": "wertr#aa.com",
"address": "Rishon LeZion"
}
];
//get headers and create them
const table = $("table");
const thead = $("thead");
var promiseMe = new Promise(function(resolve, reject) {
//to create the headers first based on the objects
var createHeaders = json.forEach((childObjects, index) => {
const kNames = Object.keys(childObjects);
for (let [index, name] of kNames.entries()) {
const actualName = name.replace(/\s+/g, '')
let divId = name.replace(/\s+/g, '-');
let element = document.getElementById(divId);
if (!element) {
thead.append("<td class='header-name' id='" + divId + "'>" + name + "</td>")
}
}
resolve(createHeaders);
})
}).then(createFields());
function createFields() {
const keyNames = Object.values(json);
keyNames.forEach((childObject, childIndex) => {
//create a row for each object
const valArray = Object.values(childObject);
$("#Values").append("<tr id='object-" + childIndex + "' class='rows table-row'></tr>")
valArray.forEach((value, index) => {
$("#object-" + childIndex).append("<td class='cell'>" + value + "</td>")
})
})
}
.cell, .header-name {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table_id" class="display">
<thead>
</thead>
<tbody id="Values">
</tbody>
</table>

Javascript - How to compare the element value inside event listener to the the array element?

Once again, I need your input on the problem that I am having now.
I am creating a MCQ trivia where I encounter a logic problem.
Although for this example, I purposely set the answer are B, C or D, the result div will always show the result is correct – although I only set an event listener on button A but no answer.
Based on my code below, am I comparing the element value with the array answer value the right way?
var exam=[{
"question": "Q1?",
"option": ["A","B","C","D"],
"answer": "B"
},{
"question": "Q2?",
"option": ["A","B","C","D"],
"answer": "C"
},{
"question": "Q3?",
"option": ["A","B","C","D"],
"answer": "D"
},{
"question": "Q4?",
"option": ["A","B","C","D"],
"answer": "B"
},{
"question": "Q5?",
"option": ["A","B","C","D"],
"answer": "C"
}]
//dom selector
var container = document.getElementById('container');
var questionEl = document.getElementById('question');
//for the answer display
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
//for the input button click
var opta = document.getElementById('opta');
var optb = document.getElementById('optb');
var optc = document.getElementById('optc');
var optd = document.getElementById('optd');
//
var button = document.querySelectorAll('button');
var nextButton = document.getElementById('help1Button');
var resultCont = document.getElementById('result');
//display question and answer
function displayQues() {
//select one question randomly from the quiz array
var i = Math.floor(Math.random() * exam.length);
questionEl.textContent=exam[i].question;
opt1.textContent = exam[i].option[0];
opt2.textContent = exam[i].option[1];
opt3.textContent = exam[i].option[2];
opt4.textContent = exam[i].option[3];
};
//load this when page load
displayQues();
opta.addEventListener("click", function() {
if (opt1.value === exam.answer) {
displayQues();
resultCont.textContent = "Correct!";
} else {
resultCont.textContent = "Incorrect!";
}
});
<div id="container">
<div class="title"> Alan Koh Exam Question</div>
<div id="question"> </div>
<button id="opta"> A: <span id="opt1"></span> </button>
<button id="optb"> B: <span id="opt2"></span> </button>
<button id="optc"> C: <span id="opt3"></span> </button>
<button id="optd"> D: <span id="opt4"></span> </button>
<div id="result"></div>
The problem with your current code is opt1.value === exam.answer. Both these properties are undefined. opt1.value because it's not set (I believe you want opt1.textContent) and exam.answer because exam is an array. You get Correct! always since undefined === undefined is true
Your issue can be solved by returning the current displayed question and using it for comparison.
var exam = [{
"question": "Q1?",
"option": ["A", "B", "C", "D"],
"answer": "B"
}, {
"question": "Q2?",
"option": ["A", "B", "C", "D"],
"answer": "C"
}, {
"question": "Q3?",
"option": ["A", "B", "C", "D"],
"answer": "D"
}, {
"question": "Q4?",
"option": ["A", "B", "C", "D"],
"answer": "B"
}, {
"question": "Q5?",
"option": ["A", "B", "C", "D"],
"answer": "C"
}]
//
//dom selector
var container = document.getElementById('container');
var questionEl = document.getElementById('question');
//for the answer display
var opt1 = document.getElementById('opt1');
var opt2 = document.getElementById('opt2');
var opt3 = document.getElementById('opt3');
var opt4 = document.getElementById('opt4');
//for the input button click
var opta = document.getElementById('opta');
var optb = document.getElementById('optb');
var optc = document.getElementById('optc');
var optd = document.getElementById('optd');
//
var button = document.querySelectorAll('button');
//
var nextButton = document.getElementById('help1Button');
var resultCont = document.getElementById('result');
//display question and answer
function displayQues() {
//select one question randomly from the quiz array
var i = Math.floor(Math.random() * exam.length);
questionEl.textContent = exam[i].question;
opt1.textContent = exam[i].option[0];
opt2.textContent = exam[i].option[1];
opt3.textContent = exam[i].option[2];
opt4.textContent = exam[i].option[3];
return exam[i]; // Return the chosen exam variable
};
//load this when page load
var currentExam = displayQues(); // Store the chosen exam
opta.addEventListener("click", function() {
if (opt1.textContent === currentExam.answer) {
currentExam = displayQues(); // Store the new question
resultCont.textContent = "Correct!";
} else {
resultCont.textContent = "Incorrect!";
}
});
<div id="container">
<div class="title"> Alan Koh Exam Question</div>
<div id="question"> </div>
<button id="opta"> A: <span id="opt1"></span> </button>
<button id="optb"> B: <span id="opt2"></span> </button>
<button id="optc"> C: <span id="opt3"></span> </button>
<button id="optd"> D: <span id="opt4"></span> </button>
<div id="result"></div>
Here is the jsfiddle link with the corrected code.
You have to loop through exam and compare the correct question and answer.

Output array to element classes

I'm trying to output a JSON object to different parts of an HTML page using the same classes.
I'm importing my JSON from an API but when I've put information into it (via input fields) it looks a little bit like this:
{
"trip": [
{ // the first object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "12:04"
},
"destination": {
"name": "Albany",
"time": "1:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "2:05"
},
"destination": {
"name": "Boston",
"time": "3:12"
}
}]
},
{ // the second object in the trip-array
"leg": [{
"tripid": "0",
"origin": {
"name": "New York",
"time": "1:04"
},
"destination": {
"name": "Albany",
"time": "2:49"
}
},{
"tripid": "1",
"origin": {
"name": "Albany",
"time": "3:05"
},
"destination": {
"name": "Boston",
"time": "4:12"
}
}]
}]
}
I'm trying to display the information on my website, but I can't get it to behave the way I want it to.
The first time around I did it something like this (after fetching the JSON via my PHP-page):
function addDataToHTML(data){
var trips = data.trip;
$.each(trips, function(){
document.getElementById('show_all_results');
var summary = document.createElement('div');
summary.innerHTML = "<span class='origin_time'>" + this.leg[0].origin.time +
" </span><span class='origin_name'> " + this.leg[0].origin.name +
"</span><span>-</span><span class='destination_time'>" + this.leg[leg.length-1].destination.time +
" </span><span class='destination_name'> " + this.leg[this.leg.length-1].destination.name +
"</span>";
document.getElementById('show_all_results').appendChild(summary);
});
}
This works but the problem I'm having is that I want to add a button in the code which would give me more information via a display:block/none-functionality. The button (and the rest of the information) would be created similarly with me having to write it in the innerHTML part of the JS, but all the ways that I've tried haven't worked and I guess it's all about me creating the divs and other DOM objects in the JS code which means that the HTML doesn't really recognize them.
Anyhow, to get more control of the code I'm now trying something like this with the HTML:
<div id="show_all_results">
<div id='search_result_single'> // First results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
<div id='search_result_single'> // Second results....
<div id='search_result_from_box'>
<span class="origin_time"></span>
<span class="origin_name"></span>
</div>
<div id='search_result_divider'>
<span>-</span>
</div>
<div id='search_result_to_box'>
<span class='destination_time'></span>
<span class='destination_name'></span>
</div>
</div>
...and so on.
</div>
The JS:
for (var i = 0; i < this.leg.length; i++) {
var originName = document.getElementsByClassName("origin_name");
var originTime = document.getElementsByClassName("origin_time");
var destTime = document.getElementsByClassName("destination_time");
var destName = document.getElementsByClassName("destination_name");
for (var x = 0; x < originName.length; x++) {
var originNameItem = originName[x];
originNameItem.innerHTML = this.leg[0].origin.name;
}
for (var y = 0; y < originTime.length; y++) {
var originTimeItem = originTime[y];
originTimeItem.innerHTML = this.leg[i].origin.time;
}
for (var z = 0; z < destTime.length; z++) {
var destTimeItem = destTime[z];
destTimeItem.innerHTML = this.leg[this.leg.length - 1].destination.time;
}
for (var a = 0; a < destName.length; a++) {
var destNameItem = destName[a];
destNameItem.innerHTML = this.leg[this.leg.length - 1].destination.name;
}
}
Is there anybody that can help me get each part of the leg-array into different parts of the page using the same classes as I've done? Or is there a better way?
This became really long, sorry about that, but please let me know if I can provide any additional information. Thanks!

Categories

Resources