Show parsed JSON data in a list - javascript

I have a JSON file with data that is downloaded from my SQL server. I parse the data with the following code:
var dataParsed = JSON.parse(data);
var dataString = JSON.stringify(data)
var interestsVar = document.getElementById("interests").innerHTML
var result = dataParsed.filter(x => x.interests === interestsVar);
var resultString = JSON.stringify(result)
var matchesID = document.getElementById("matches")
var tagLi = matchesID.getElementsByTagName("li")
var li = "<li>" + resultString + "</li>";
if (document.getElementById("matches").innerHTML.includes(li)) {
} else {
document.getElementById("matches").innerHTML = document.getElementById("matches").innerHTML + li;
document.getElementById("matchesCount").innerHTML = "You have " + tagLi.length + " matches."
count()
}
That all works, I am able to get the data in the list that matches the search/interests box. I currently have it so it displays them in a list. I am wondering if there is a way to make them show up in a box and when they click a button they can either mark them as "ok" or "no", and basically shuffle through the options.

Related

how to list all local storage on page properly in javascript?

I am trying to show all my localstorage items value on my index page but for some reason it is not showing. can anyone see what I am doing wrong in my code below. In my index page script I am looping thorough the length of local storage and trying to display them on screen, only thing that display is one item. Please help. thanks for your help.
here is my code (index page script):
document.addEventListener("DOMContentLoaded", function (event) {
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
})
The other script where I load it to localStorage:
var addToTheContent = document.getElementById("canvas");
var scheduleEvent = document.getElementById("scheduleStartTime");
var candidateId = document.getElementById('candsId');
var getCandId = document.getElementById("candsId");
var displayCandId = candidateId.options[candidateId.selectedIndex].value;
var id = 1;
function addTheEvent() {
var showText = addToTheContent.innerHTML = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText))
id += 1
localStorage.getItem(`key${id}`);
window.location = "/";
}
"key${id}" is a template string, you need to use backticks `` instead of quotation marks "".
You could also loop through localStorage as you normally would for most JavaScript objects:
for(var key in localStorage) {
if(localStorage.hasOwnProperty(key)) { // ignore the prototype methods
// Do whatever you want with key and value found here
console.log(key + ": " + localStorage[key]);
}
}
Typo: Use i instead id
var dataFromLocalStorage = localStorage.getItem(`key${id}`);
correct:
var dataFromLocalStorage = `localStorage.getItem("key${i}");
Another thing, You are updating same innerHTML
var dataFromLocalStorage = "";
for (var i = 0; i < localStorage.length; i++) {
dataFromLocalStorage =
dataFromLocalStorage + " " + localStorage.getItem(`key${i}`);
}
document.querySelector("#content").innerHTML = dataFromLocalStorage; // Updating same thing
// do something with localStorage.getItem(localStorage.key(i));
// missing template string 'key${id}'
var id = 1;
function addTheEvent() {
var showText = displayCandId + " ( " + scheduleEvent.value + " ) ";
localStorage.setItem(`key${id}`, JSON.stringify(showText));
id += 1;
window.location = "/";
}

How can I make sure each dynamically created image is taking on its own information/data pulled from the API?

Is there a way for me to make sure each img tag created also contains or can be linked with its individual data from the api? If only one image is returned in the search, it will give me the data for that image. However, if multiple images are returned, once clicked, it will return a only one possible image and data. I am new to coding and javascript in general, so please forgive any rookie mistakes. Thanks!
var scryfallURL = "https://api.scryfall.com/cards/search?q=";
var cardName = "";
var container = $("#list");
$("#searchBtn").on("click", function(event) {
event.preventDefault();
container.empty();
cardName = $("#search").val().trim();
queryURL = scryfallURL + cardName;
$.ajax({
url: queryURL,
method: "GET"
}).then(function(response) {
debugger;
var result = response.data;
console.log(result);
$('#search').val('');
//loops through creating an image tag for each search result
for (let index = 0; index < result.length; index++) {
var showCard = $("#list").append("<image src=' " + result[index].image_uris["normal"] + "' ></image>", "</br>");
var name = result[index].name + "<br>";
var creature = result[index].type_line + "<br>";
var flavorText = result[index].flavor_text + "<br>";
var legality = result[index].legalities + "<br>";
var cardFront = "<image src=' " + result[index].image_uris["large"] + "' ></image>" + "<br>";
};
// click function to clear the div and replace with only one card image and info
showCard.click(function() {
$("#searchForm").empty();
container.empty();
$("#info").append(name, creature, flavorText, legality);
$("#oneCard").append(cardFront);
})
});
});

How to get values data from child

How to get last 20 records from firebase? I got:
dataset: undefined undefined
My firebase looks like this:
my code
var rootRefData = db.ref().child("users_db/user1/dataset");
rootRefData.once("value", snap => {
var key = snap.key;
var timestamp = snap.val().timestamp;
var log = snap.val().log;
var custom = "";
// create line chart
custom += key + ": " + timestamp + " " + log + "<br />";
console.log(custom);
counter++;
$("#chartsl-container-all").append(custom);
});
Try this:
var rootRefData = db.ref().child("users_db/user1/dataset");
rootRefData.once("value", snap => {
snap.forEach(function (snapshot) {
var key = snapshot.key;
var timestamp = snapshot.val().timestamp;
var log = snapshot.val().log;
var custom = "";
rootRefData is at node dataset, since you want to get timestamp and log, then you need to iterate inside the randomid using forEach to be able to get those values and the random id.

How can I print values of nested objects of JSON string?

I have the following JSON response after an XMLHttpRequest:
{
"success":true,
"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
I want to display all the questions in a bulleted list and all the answers in a bulleted list side-by-side. Right now I have the following (I included this code to add the JSON.parse functionality, should work):
<script type="text/javascript" src="json2.js"></script>
// ...
var response = JSON.parse(xhr.requestText);
var list = document.getElementById('listQuestions');
for (var i = 0 ; i < response.length; i++){
list.innerHTML += '<li>' + response[i].question + '</li>'; // I'm certain this is wrong--I also tried the following but it's not what I'm looking for:
// for (var key in response) {
// console.log("Key: "+key+" value: "+response[key]);
// }
}
// ...
</script>
The result property in your JSON response is an object and not an array. Also, the response variable does not point to the result object but rather the parent, container object so you'll have to access the result object by calling response.result.
var jsonText = '{"success":true,"result":{"1":{"id":"1","question":"What is one + two","answer":"three"},"2":{"id":"2","question":"two + four","answer":"six"},"3":{"id":"3","question":"one + three","answer":"for"}}}';
var response = JSON.parse(jsonText);
var list = document.getElementById('listQuestions');
var results = Object.keys(response.result);
for (var i = 1 ; i <= results.length; i++) {
list.innerHTML += '<li>' + response.result[i].question + ' - ' + response.result[i].answer + '</li>';
}
<div id="listQuestions">
</div>
https://jsfiddle.net/djqrt8z9/
Based on your description I wasn't sure if you wanted two lists because you say you wanted a bulleted list of questions and bulleted list of answers.
var response = {
"success":true,
"result":{
"1":{"id":"1","question":"What is one + two","answer":"three"},
"2":{"id":"2","question":"two + four","answer":"six"},
"3":{"id":"3","question":"one + three","answer":"for"}
}
}
var questions = document.getElementById('listQuestions');
var answers = document.getElementById('listAnswers');
var result = response.result
Object.keys(result).forEach(function(key){
var question = document.createElement('li');
questions.appendChild(question);
question.innerHTML = result[key].question;
var answer = document.createElement('li');
answers.appendChild(answer);
answer.innerHTML = result[key].answer;
})
<ul id="listQuestions"></ul>
<ul id="listAnswers"></ul>
let response = JSON.parse(xhr.requestText);
let qs = [];
for (let obj of response.result) qs.push("<li>"+obj.question+"<\/li>");
document.getElementById('listQuestions').innerHTML = qs.join('');
The above uses the for ... of construct to loop through the values of an object.

trying to use data detail in buttons but getting a unexpected error

I am using the following code which displays my items from a database on the screen. I have tried adding a button to each of them using data detail as this is how i am passing data through local storage. However when i run this code i get an error message with an unexpected { in the html += line, can you not do this?
function display(results) {
article = document.getElementById("homeArticle");
var html = '';
for (var i = 0; i < results.length; i++){
var item = results[i];
var name = item.P_NAME;
var description = item.P_DESCRIPTION;
var price = item.P_PRICE;
var quant = item.P_QUANTITY;
// next I add to the string that we want to place on the page
html += '<section id="homePageSection"><div id="test"> <p>Name: ' + name + '</p><p>Description: ' + description + '</p><p>Price: £' + price + '</p><p>Quantity: ' + quant + '</p><button data-detail='{"name":"banana", "cost": "19"}'>Bananas</button></div></section>';
};
article.innerHTML = html;
}
function getItems() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var results = JSON.parse(this.responseText);
display(results.rows);
};
xhr.open("GET", "displayData.php");
xhr.send();
}
window.addEventListener("load", getItems);
You need to escape the the ' around your stringed object using backslash.
Like this
'<button data-detail=\'{"name":"banana", "cost": "19"}\'>Bananas</button>'
You would need to escape the single quotes inside your string:
'</p><button data-detail=\'{"name":"banana", "cost": "19"}\'>Bananas</button></div></section>'

Categories