Displaying results, in different div's from a JavaScript loop - javascript

var parseResponse = function() {
var data = JSON.parse(this.response);
console.log (data);
var head = "Cheapest Flight to " + document.getElementById('search_term1').value;
var bodystuff = document.createElement('h4');
bodystuff.innerHTML = head;
document.getElementById('right1').appendChild(bodystuff);
for (var i=0; i<data.results.length; i++) {
try {
var printDeparture = "Depart: " +
data.results[i].itineraries[i].outbound.flights[i].departs_at;
var bodystuff = document.createElement('p');
bodystuff.innerHTML = printDeparture;
document.getElementById('right1').appendChild(bodystuff);
console.log(printDeparture);
} catch (err) {
console.log(data.results[i]);
}
}
}
I am trying to get each result printed out in a separate div (currently, I have 3 results back) but can only print out the first of the three, I have tried to increase [i] in each of the results, and changed the divs from "right1" to "left1" but nothing happens. any help?
Here is my HTML code;
<div class="wrap">
<div class="left">
<img src="Assets/China.png" class="pics">
</div>
<div class="right" id="right1">
</div>
</div>
<div class="wrap">
<div class="left" id="left1">
</div>
<div class="right" >
<img src="Assets/hotel.jpg" class="pics">
</div>
</div>
and here is the result I get back from the API:
Object
results
:
Array[3]
0
:
Object
1
:
Object
2
:
Object
(hope it makes sense)

Related

How can i make 3 col in a row an 2 col in a row (bootstrap) with javascript?

I'm a beginner in JavaScript. I've got a problem.
I need to create some elements and I need to put my API's data is these elements. But I want to create 3 cards (bootstraps) in my first row and 2 in my second row.
But I think my loop isn't ok. Because all my data are on my fifth card.
That's my code HTML and JavaScript:
HTML :
</section>
<section class="container">
<div class="row">
<div id="colCam1" class="col-12 col-lg-4"></div>
<div id="colCam2" class="col-12 col-lg-4"></div>
<div id="colCam3" class="col-12 col-lg-4"></div>
</div>
<div class="row">
<div id="colCam4" class="col-12 col-lg-4"></div>
<div id="colCam5" class="col-12 col-lg-4"></div>
</div>
</section>
JS :
fetch("http://localhost:3000/api/cameras")
.then((response) =>
response.json().then ((data) => {
console.log(data);
for(i=0; i < data.length; i++) {
let indexCard = document.createElement("div");
let indexImg = document.createElement("img");
let indexBodyCard = document.createElement("div");
let indexProductTitle = document.createElement("h5");
let indexProductPrice = document.createElement("p");
colCam1.appendChild(indexCard);
colCam2.appendChild(indexCard);
colCam3.appendChild(indexCard);
colCam4.appendChild(indexCard);
colCam5.appendChild(indexCard);
indexCard.classList.add("card");
indexCard.appendChild(indexImg);
indexImg.classList.add("card-img-top");
indexCard.appendChild(indexBodyCard);
indexBodyCard.classList.add("card-body");
indexBodyCard.appendChild(indexProductTitle)
indexProductTitle.classList.add("card-title");
indexBodyCard.appendChild(indexProductPrice);
indexProductPrice.classList.add("card-text");
indexProductTitle.innerHTML = data[i].name;
indexProductPrice.innerHTML = parseInt(data[i].price) + " €";
indexImg.setAttribute("src", data[i].imageUrl);
}
})
);
That's the result on my inspector :
Result of my code
Thx for your help
If I understood correctly, you are only expecting to get 5 elements from your API and you want to put each of them in one column. If that's the case, you can put your column elements in an array and index them accordingly in your loop like so:
const cols = [colCam1, colCam2, colCam3, colCam4, colCam5]
for(i=0; i < data.length; i++) {
let indexCard = document.createElement("div");
let indexImg = document.createElement("img");
let indexBodyCard = document.createElement("div");
let indexProductTitle = document.createElement("h5");
let indexProductPrice = document.createElement("p");
cols[i].appendChild(indexCard);
indexCard.classList.add("card");
indexCard.appendChild(indexImg);
indexImg.classList.add("card-img-top");
indexCard.appendChild(indexBodyCard);
indexBodyCard.classList.add("card-body");
indexBodyCard.appendChild(indexProductTitle)
indexProductTitle.classList.add("card-title");
indexBodyCard.appendChild(indexProductPrice);
indexProductPrice.classList.add("card-text");
indexProductTitle.innerHTML = data[i].name;
indexProductPrice.innerHTML = parseInt(data[i].price) + " €";
indexImg.setAttribute("src", data[i].imageUrl);
}
This code is going to break if your API returns more than 5 elements. You could try something like cols[i % 5].appendChild(indexCard); or consider other layout strategies.

Getting id of div

1) I am rendering messeages according to JSON. Firstly, I need to show only 3 information from that JSON (JSON has 6 attrs). When user click on the rendered message, it should show additional information like description and I need get id of that div... Problem is, I cannot access that id...
I have main div messages, and then message_items are added to this div according to json. When I am trying to get ID of that div, it writes undefined...
My code looks like:
2) How to store additional information about that div which I dont want to be visible?
$(".messages").on('click','.message__item', function(e) {
documentView.clearContent();
var targetElement = event.target || event.srcElement;
alert(targetElement);
var id = $(this).attr("id"); // DOES NOT WORK - UNDEFINED
alert(contentPanelId);
const data = {
title: $(this).find(".title").text(),
date: $(this).find(".date").text(),
desc: document.getElementById("descr").value,
createdBy: document.getElementById("createdBy").value,
id: targetElement.id // DOES NOT WORK, UNDEFINED
};
documentView.renderDocument(data);
});
export const fillDocuments = (data) => {
console.log("DATA. "+ data);
for(var i = 0; i < data.length; i++){
const markup = `
<div class="message__item id=${data[i].id}>
<img src="../img/copy.svg" class="item-type">
<div class="title">
${data[i].title}
</div>
<div class="date">
${formatTimeForMessages(data[i].uploadDatetime)}
</div>
<div class="read">
XY
</div>
// THIS DOES NOT WORK FOR ME AGAIN
<input type="hidden" id="descr" value="${data[i].description}"></input>
<input type="hidden" id="createdBy" value="Someone"/>
</div>`;
console.log("MRK "+ markup);
elements.messages.insertAdjacentHTML("beforeend", markup);
}
};
First, your didn't close the class quote on near "message__item" name. And how store data in a way that isn't visible? use data attribute, se here. Bellow a working example.
$(".messages").on('click','.message__item', function(e) {
///documentView.clearContent();
var targetElement = event.target || event.srcElement;
alert(targetElement.nodeName);
console.log(this);
var id = $(this).attr("id"); // DOES NOT WORK - UNDEFINED
alert(id);
alert(this.dataset.title);
const data = {
title: $(this).find(".title").text(),
date: $(this).find(".date").text(),
desc: document.getElementById("descr").value,
createdBy: document.getElementById("createdBy").value,
id: targetElement.id // DOES NOT WORK, UNDEFINED
};
//documentView.renderDocument(data);
});
var fillDocuments = (data) => {
for(var i = 0; i < data.length; i++){
const markup = `
<div class="message__item" data-title="${data[i].title}" id=${data[i].id}>
<img src="../img/copy.svg" class="item-type">
<div class="title">
${data[i].title}
</div>
<div class="date">
${(data[i].uploadDatetime)}
</div>
<div class="read">
XY
</div>
// THIS DOES NOT WORK FOR ME AGAIN
<input type="hidden" id="descr" value="${data[i].description}"></input>
<input type="hidden" id="createdBy" value="Someone"/>
</div>`;
$("#messages").get(0).insertAdjacentHTML("beforeend", markup);
}
};
fillDocuments([
{id:1, uploadDatetime:Date(), title: 'Title here', description: 'Desc...'}
])
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="messages" class="messages">
</div>

Consume formatted string into three different elements

I have code that cuts up a tilte that is formatted like:
TITLE1 - TITLE2 [XXX]
With the three parts getting "parsed" into an array of three pieces and inserted into three div elements:
<div class='title'>
<div class='title2'>
<div class='cut'>
That code is:
var Enumber1 = new Array();
$("#title").each(function(i){
var text = $(this).text();
if(text.indexOf('[') != -1 || text.indexOf(']') != -1){
var Ntext1 = text.split('[')[0];
Enumber1[i] = text.split('[')[1].split(']')[0];
$(this).text(Ntext1);
}
});
$("#cut").each(function(i){
$(this).fadeIn("slow");
if(Enumber1[i] != undefined){
$(this).text(Enumber1[i]);
} else {
$(this).css('N/A');
}
});
So far, I get:
TITLE1 - TITLE2 >>> stay in div class="title"
XXX >>>> cut div class"cut"
What I want is to get this text into:
TITLE1 >>> Stays in <div class"title">
TITLE2 >>> Moves to <div class"title2">
XXX >>> Moves to <div class"cut">
So that the final HTML looks like this:
<div class='title'>
TITLE1
</div>
<div class='title2'>
TITLE2
</div>
<div class='cut'>
XXX
</div>
See https://jsfiddle.net/bro69zvb/6/ for my current code.
You can simply use a split function at the end of your code:
var Enumber1 = new Array();
$(".title").each(function(i){
var text = $(this).text();
if(text.indexOf('[') != -1 || text.indexOf(']') != -1){
var Ntext1 = text.split('[')[0];
Enumber1[i] = text.split('[')[1].split(']')[0];
$(this).text(Ntext1);
}
});
$(".cut").each(function(i){
$(this).fadeIn("slow");
if(Enumber1[i] != undefined){
$(this).text(Enumber1[i]);
}else{
$(this).css('N/A');
}
});
// Get the text from <div class="title>
var titleText = $(".title").text();
//TITLE:
// Get the text before the " - "
title = titleText.split(" - ")[0];
// Put the result inside <div class="title">
$(".title").html(title);
//TITLE2:
// Get the text after the " - " before the next space
title2 = titleText.split(" - ")[1].split(" ")[0];
// Put the result inside <div class="title2">
$(".title2").html(title2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
Tile1 - Tile2 [XXX]
</div>
<div class="title2">
</div>
<div class="cut">
</div>

How to iterate through HTML entities with javascript

I have the following HTML [below]. I am trying to iterate through all DOM with class="gmvcRow", and grab the text in all of the "gmvcCell" for each 'gmvcRow'. I would like to place all the text in an array(['firstname', 'lastname', 'dob', 'city']). And i would like to place this array into another array that holds "arrays of gmvcRow". My attempt is below but i am still not successful. I understand that the text in 'gmvcCell' is in itself another label node.
<div class="gmvcRow">
<div class="gmvcCell">firtname</div>
<div class="gmvcCell">lastname</div>
<div class="gmvcCell">dob</div>
<div class="gmvcCell">city</div>
</div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>
my code:
var gmvcRowArray = document.getElementsByClassName('gmvcRow');
console.log('number of records: ' + gmvcRowArray.length);
// Master array
var masterArray = [];
// Iterate through array
for(var i=0; i<gmvcRowArray.length; i++){
// Iterate through all childNodes
var rowArray = [];
for(var c=0; c<gmvcRowArray[i].childNodes.length; c++){
c = c + 1; // skip non text node
console.log('c: '+c);
if(gmvcRowArray[i].childNodes[c] != null){
var value = gmvcRowArray[i].childNodes[c].innerHTML;
rowArray.push(value);
//console.log('rowArray.length: '+rowArray.length);
console.log('value: '+value);
}
c = c - 1;
}
// Add row to master array
masterArray.push(rowArray);
console.log('masterArray.lengh: '+masterArray.length);
}
Using childNodes makes it harder than needed, since it also selects text nodes.
Instead use some of the ES6 features, which lead to concise code:
var arr = Array.from(document.querySelectorAll('.gmvcRow'), row =>
Array.from(row.querySelectorAll('.gmvcCell'), cell => cell.textContent)
);
console.log(arr);
<div class="gmvcRow">
<div class="gmvcCell">firstname</div>
<div class="gmvcCell">lastname</div>
<div class="gmvcCell">dob</div>
<div class="gmvcCell">city</div>
</div>
<div class="gmvcRow">
<div class="gmvcCell">Helene</div>
<div class="gmvcCell">Johnson</div>
<div class="gmvcCell">11/11/1995</div>
<div class="gmvcCell">Paris</div>
</div>
Quick sample for 1-level nesting
var rows = Array.from(document.getElementById('container').querySelectorAll('.gmvcRow'));
const result = rows.map(row => {
return Array
.from(row.querySelectorAll('.gmvcCell'))
.map(cell => cell.innerText);
});
console.log(result);
https://jsfiddle.net/snba2qsf/
After all you can filter result to exclude empty arrays
In your Script: Just check the value before adding to row array whether Is not null and not undefined.
if(value != null || value != undefined)
{
rowArray.push(value.trim());
}
Here is my answer using querySelectorAll
var gmvcRowArray = [];
document.querySelectorAll('.gmvcRow').forEach((el, idxRow) =>{
var gmvcCellArray = [];
el.querySelectorAll('.gmvcCell')
.forEach((el) =>{
gmvcCellArray.push(el.innerText);
});
gmvcRowArray.push(gmvcCellArray)
})
console.log(gmvcRowArray)
<div class="gmvcRow">
<div class="gmvcCell">Name1</div>
<div class="gmvcCell">lastname1</div>
<div class="gmvcCell">dob1</div>
<div class="gmvcCell">city1</div>
</div>
<div class="gmvcRow">
<div class="gmvcCell">Name2</div>
<div class="gmvcCell">lastname2</div>
<div class="gmvcCell">dob2</div>
<div class="gmvcCell">city2</div>
</div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>
<div class="gmvcRow"></div>

How to render data object from JSON in bootstrap columns in jQuery

How can I render objects from GET call to my html and wrap the data in bootstrap col-*
Trying to rendering it to something like this
<div class="col-sm-4">
<div class="thumbnail">
<img src="./assets/imgs/products/coke-medium.png" alt="...">
<div class="caption">
<p>Coke 500ml</p>
<p>
<b>£1.99</b>
Add
</p>
</div>
</div>
</div>
This is my GET function, however in the foreach it's only giving me the last item name. Also is there a better way of doing this than what I'm trying to do below?
function getDrinks() {
$.get('./assets/products.json')
.then(function (data) {
console.log(data.drinks);
var drinks = data.drinks;
for (var i = 0; i < drinks.length; i++) {
var element = drinks[i];
$('#drink_list').html('<div class="col-sm-4">' + element.name + '</div>');
}
})
}
JSON sample --
{
"drinks":[
{
"name": "Coke",
"liter": "500ml",
"image": "/products/coke-medium.png"
},
}
the function html replace the content of drink_list. you need to use append http://api.jquery.com/append/
for (var i = 0; i < drinks.length; i++) {
var element = drinks[i];
$('#drink_list').append('<div class="col-sm-4">' + element.name + '</div>');
}

Categories

Resources