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

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>');
}

Related

how to get and render selected values related data from array in jquery?

I have no expertise in javascript but I want to render this data which is showing in my console.log below
How can I make forloop or something like that to render this data in my html input?
create.html
<div class="col-sm-2">
<div class="form-group">
<label>Expected Values</label>
<input type="text" class="form-control" value="{{vital.expected_values}}" readonly>
</div>
</div>
<div class="col-sm-2">
<div class="form-group">
<label>Price</label>
<input type="text" class="form-control" value="{{vital.price}}" readonly>
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#id_vitals").change(function () {
var vitals = $(this).val();
$.ajax({
url: $('#personForm').data('url'),
data: { 'vital_id': vitals },
success: function (response) {
console.log(response[vitals['name']])
}
});
});
})
</script>
I would do it somehow like that:
// Your data
let dataArray = [{data: 1, otherData: 2, elseData: 3}]
// The element, where you want to show it
let targetElement = document.getElementById('your-targer-id');
// The container element for elements
let newContainer = document.createElement('ul');
// Pure JS loop, easy to understand what is happening
// But you can also do it with .map();
for (let i = 0; i < dataArray.length; i++) {
// Add every line
newContainer.innerHTML+='<li>' + dataArray[i].data + '</li>';
// Or other things, depending how you want to show the data
newContainer.innerHTML+='<li> data value is: ' + dataArray[i].data + ' and otherData value is: ' + dataArray[i].otherData + '</li>'; //etc
}
// Append created list in target element
targetElement.appendChild(newContainer);
EDIT - now I see, that you want to display multiple values in text input, rather like so:
let dataArray = [...your-data-array]
let targetElement = document.getElementById('target-input');
for (let i = 0; i < dataArray.lenght; i++) {
// loop throug elements and add it to value attribute of input, separated by coma.
targetElement.value+=dataArray[i].expected_values + ', ';
}

add div id and for attribute sequentially using js

I want to dynamically add the id and for attribute for each input and label element.
<div id="splash">
<div class="tab">
<input id="tab-1">
<label for="tab-1"><label>
</div>
<div class="tab">
<input id="tab-2">
<label for="tab-2"><label>
</div>
<div class="tab">
<input id="tab-3">
<label for="tab-3"><label>
</div>
</div>
So basically I would want the id for the input to be tab-# with the # increasing by 1 for each input field and the same for the "for=" attribute for the label.
It's super easy. Just iterate through each .tab, using each's index argument, and modify the attributes of the elements.
$('.tab').each(function (index) {
var tabName = 'tab-' + (index + 1);
$('input', this).attr('id', tabName);
$('label', this).attr('for', tabName);
});
Jsbin: http://jsbin.com/rawatag/4/edit?html,js,output
Ok.
I won't give you a straight answer but this should be more useful in future.
Basically make the container <div id=splash>
Then run this command document.getElementById("parentID").innerHTML += "Something here"
This will add the content (pay attention to. The += sign) to the div (splash)
Then, just wrap this in a loop using a counter to get the desired result
Eg: ...innerHTML += "<div id=tab-" + counter + "></div>"
Note that this can be done in raw JS. No JQuery required.
No need for jQuery here:
es5 (jsfiddle)
function assignInputsAndLabels(root) {
var children = root.children;
var tabNumber = 1;
for (var i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', 'tab-' + tabNumber);
children[i].getElementsByTagName('label')[0].setAttribute('for', 'tab-' + tabNumber);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
es6
function assignInputsAndLabels(root) {
const children = root.children;
let tabNumber = 1;
for (let i = 0; i < children.length; i++) {
if (children[i].classList.contains('tab')) {
children[i].getElementsByTagName('input')[0].setAttribute('id', `tab-${tabNumber}`);
children[i].getElementsByTagName('label')[0].setAttribute('for', `tab-${tabNumber}`);
tabNumber++;
}
}
}
assignInputsAndLabels(document.getElementById('splash'));
The parameter to the function is the wrapper of the elements that have the class of tab. In your case, you'd pass in the DOM node of the element with id of splash. So you'd call the function like this:
assignInputsAndLabels(document.getElementById('splash'));
I have done it using javascript.Check it below
function init(){
var sel = document.getElementsByClassName("tab");
var i=1;
for(let obj of sel){
var attr = "tab-"+i;
obj.getElementsByTagName('input')[0].setAttribute("id",attr);
obj.getElementsByTagName('label')[0].setAttribute("for",attr);
i++;
}
}
addEventListener("load",init);
<div class="tab">
<input type="text">
<label></label>
</div>
<div class="tab">
<input type="text">
<label></label>
</div>

How to get the text from a div which has children in it

I am currently studying JavaScript and I have the following problem. Is it possible to get only the text from a div which has children inside it? I managed to make it work only for the text which appears before the div's children.
PS: I would like to mention that I am trying to achieve this using only pure JavaScript.
var Class = document.querySelectorAll('div,b');
for (var i=0; i < Class.length; i++){
console.log(Class[i].childNodes[0].nodeValue);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
It's not very clean way, but try something like this :
//get all div's with Bio css class (You can change it)
var Class = document.querySelectorAll('.Bio');
var sp=document.getElementById('res');
var arr=[]; //I put result into array so You can use it where You need
for (var i=0; i < Class.length; i++) {
for(var x=0;x<Class[i].childNodes.length;x++) {
if(Class[i].childNodes[x].nodeValue==null) {
//get value, innerHTML, from <b>
//res.innerHTML+=Class[i].childNodes[x].innerHTML+'<br>';
arr.push(Class[i].childNodes[x].innerHTML);
} else {
//get div innerHTML (before,after every child node
//res.innerHTML+=Class[i].childNodes[x].nodeValue+'<br>';
arr.push(Class[i].childNodes[x].nodeValue);
}
}
}
//show result into that span
for(var i=0;i<arr.length;i++) {
res.innerHTML+=arr[i]+'<br>';
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
<br><br>
<!-- I use this span to show result -->
<span id="res"></span>
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
var children = [];
var boldText = Class[i].querySelectorAll('b')[0].innerText;
var otherText = Class[i].innerText.split(Class[i].querySelectorAll('b')[0].innerText)
children.push(otherText[0]);
children.push(boldText);
children.push(otherText[1]);
console.log(children);
}
Output :-
["My name is ", "John Doe", " and I am coming from Texas"]
["My name is ", "Jean Frye", " and I am coming from Alabama"]
This might do the trick.
You can use innerText to get only the text of your selected element.
var Class = document.querySelectorAll('div');
for (var i=0; i < Class.length; i++){
console.log(Class[i].innerText);
}
<div class="Bio">
My name is <b>John Doe</b> and I am coming from Texas
</div>
<div class="Bio">
My name is <b>Jean Frye</b> and I am coming from Alabama
</div>
For more information, reference the MDN article on innerText

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

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)

Appending ascending images based on the id of parent div

Say I had the following three divs with unique ids on a page
<div id="product-id-001"></div>
<div id="product-id-002"></div>
<div id="product-id-003"></div>
What code would I need to add the following image elements based on the id of the div?
<div id="product-id-001">
<img src="images/product-id-001-1.jpg"></img>
<img src="images/product-id-001-2.jpg"></img>
<img src="images/product-id-001-3.jpg"></img>
</div>
<div id="product-id-002">
<img src="images/product-id-002-1.jpg"></img>
<img src="images/product-id-002-2.jpg"></img>
<img src="images/product-id-002-3.jpg"></img>
</div>
<div id="product-id-003">
<img src="images/product-id-003-1.jpg"></img>
<img src="images/product-id-003-2.jpg"></img>
<img src="images/product-id-003-3.jpg"></img>
</div>
Thanks for any tips.
$('div[id^=product]').each(function(index, elem) {
for(var i = 1; i < 4; i++) {
$('<img>', {
src: '/images/' + elem.id + i
}).appendTo(this);
}
});
Demo: http://www.jsfiddle.net/9S9Av/
(You need Firebug or another DOM inspector to see the result)
From the jQuery docs:
"The .append() method inserts the specified content as the last child of each element in the jQuery collection"
So:
$('#product-id-001").append('<img src="images/product-id-001-1.jpg"></img>');
etc...
// Select all elements with an id beginning with product-id:
var $productContainers = $('[id^=product-id]');
// Loop through the matched elements and append the images:
$productContainers.each(function () {
var $this = $(this),
productId = $this.attr('id'),
numImages = 3,
extension = '.jpg';
// Create and append the images based on the configuration above. Note that this
// assumes that each product have three valid images.
for (var i = 1; i <= numImages; i++)
{
var $image = $('<img alt="" />').attr('src', 'images/'+productId+'-'+i+extension);
$image.appendTo($this);
}
});

Categories

Resources