{
"top10": [
{
"state": "red",
"claimed": true,
"branch": "release-2.3.4",
"job": "sdk",
"culprit": "Hansi Meier"
},
{
"state": "blue",
"claimed": true,
"branch": "master",
"job": "ibeo-cloud",
"culprit": "Karl Gustavo"
},
{
"state": "yellow",
"claimed": false,
"branch": "feature-abc",
"job": "appbase",
"culprit": "MAfred Auch"
}
]
}
<nav class="side-navbar">
<div class="title">
<h1>Top 10</h1>
</div>
<ul class="list-group">
<a class="item d-flex align-items-center">
<i class="fa fa-caret-up" style="font-size:48px;color:red"></i>
<div class="item d-table-cell">
<i id='topbranch'></i>
<i id='topjob'></i>
<i id='topculprit'></i>
</div>
<i class="fa fa-refresh" style="font-size:30px;color:yellow"></i>
</a>
</ul>
</nav>
I want to insert my json data into html elemnts
for example top10[0].branch should go into html id topbranch.
and it should loop. please see the image how it should come.
please show me how to do it in javascript.it would be nice if you give jsfiddle link
You need to change all id to class for topbranch, topjob and topculprit as you will be creating multiple elements through loop. The id should be unique for any element in HTML document.
Hope the below sample works for you. You can find comments in JS code. You need to write your own CSS to display the items as per your screen shot. I have added li element under ul element.
var data = {
"top10": [
{
"state": "red",
"claimed": true,
"branch": "release-2.3.4",
"job": "sdk",
"culprit": "Hansi Meier"
},
{
"state": "blue",
"claimed": true,
"branch": "master",
"job": "ibeo-cloud",
"culprit": "Karl Gustavo"
},
{
"state": "yellow",
"claimed": false,
"branch": "feature-abc",
"job": "appbase",
"culprit": "MAfred Auch"
}
]
};
$.each(data.top10, function (i, el) {
var ele = $(".list-group a.item:first").parent().clone(); //Clone the first element
ele.find(".topbranch").text(el.branch).css("color", el.state); //Update values
ele.find(".topjob").text(el.job);
ele.find(".topculprit").text(el.culprit);
$(".list-group").append(ele); //Append cloned element to `list-group`
})
$(".list-group a.item:first").parent().remove(); //Remove first li
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<nav class="side-navbar">
<div class="title">
<h1>Top 10</h1>
</div>
<ul class="list-group" style="list-style-type: none;">
<li>
<a class="item d-flex align-items-center" style="display: flex; justify-content: space-evenly;">
<i class="fa fa-caret-up" style="font-size:48px;color:red"></i>
<div class="item d-table-cell">
<i class='topbranch'></i><br/>
<i class='topjob'></i><br/>
<i class='topculprit'></i><br/>
</div>
<i class="fa fa-refresh" style="font-size:30px;color:yellow"></i>
</a>
</li>
</ul>
</nav>
If you have json array you need to just loop through all objects and read their properties.
Please try this.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myObj, i, j, x = "";
myObj = {
"top10": [
{
"state": "red",
"claimed": true,
"branch": "release-2.3.4",
"job": "sdk",
"culprit": "Hansi Meier"
},
{
"state": "blue",
"claimed": true,
"branch": "master",
"job": "ibeo-cloud",
"culprit": "Karl Gustavo"
},
{
"state": "yellow",
"claimed": false,
"branch": "feature-abc",
"job": "appbase",
"culprit": "MAfred Auch"
}
]
}
for (i in myObj.top10) {
x += "<h2>" + myObj.top10[i].branch + "</h2>";
x += "<h2>" + myObj.top10[i].job + "</h2>";
x += "<h2>" + myObj.top10[i].culprit + "</h2>";
}
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
Try using a modern javascript framework with data binding feature, it's easy to implement and elegant, you can choose from vue, Angular or React.
You can try some thing like this iterate over your data.
var html;
$.each(data.top10,function(key1,value1){
html="<div><i id='topbranch'>"+value1.state+"</i><br>"
+"<i id='topjob'>"+value1.job+"</i><br>"
+" <i id='topculprit'>"+value1.culprit+"</i></div><br>"
$("#divId").append(html)
})
here is the fiddle : https://jsfiddle.net/6w11Ln05/3/
you can add your design accordingly.
Related
My vue data is
data: function() {
return {
results: {
"items": [
{
"id": "770c257b-7ded-437c-99b5-3b8953b5be3a",
"name": "Gsbssbb",
"price": 9559,
"colour": {
"name": "Blue",
"hex": "FF0000AE"
},
"amountAvailable": 949
},
{
"id": "8ecc6558-0c16-4497-b742-5eb5cb28c572",
"name": "Vsbdbdb",
"price": 6559,
"colour": {
"name": "Purple",
"hex": "FF800080"
},
"amountAvailable": 6595
}
],
}
The template is
<div class="column asoebi-list-item" v-for="result in results.items">
<div id="item-event" class="columns is-mobile">
<div class="column auto has-text-left">
<p class="item-name">{{result.name}}</p>
<p class="item-price" id="item-price"> {{result.price}}</p>
<p class="item-units">{{result.amountAvailable}} Units Remaining · {{result.colour.name}}</p>
</div>
<div class="column is-2">
<button id="number-spinner-up" class="o-button button-bottom" type="button" onclick="this.parentNode.querySelector('[type=number]').stepUp();">
+
</button>
<input id="count-input" type="number" name="number" min="0" max="900" v-model="count">
<button id="number-spinner-down" class="o-button button-top" type="button" onclick="this.parentNode.querySelector('[type=number]').stepDown();">
-
</button>
</div>
</div>
</div>
As i loop through each data and display them, How can I add event to hide and un-hide div with number id "number-spinner" class and buttons on each element displayed.
I have this already written, but it only affects the first item even if I click on other items.
let allItems = document.querySelectorAll("#item-event");
for (let i = 0; i <= allItems.length; i++) {
allItems[i].addEventListener("click", () => {
this.toggleSpinner()
});
}
toggleSpinner: function() {
let countInput = document.getElementById("count-input");
countInput.style.visibility = "visible"
let theElementStyle1 = getComputedStyle(document.getElementById("number-spinner-up"));
let theElementStyle2 = getComputedStyle(document.getElementById("number-spinner-down"));
if(theElementStyle1.visibility === "hidden") {
document.getElementById("number-spinner-up").style.visibility = "visible";
}
else {
if(countInput.value === "0") {
countInput.style.visibility = "hidden"
}
document.getElementById("number-spinner-up").style.visibility = "hidden";
}
if(theElementStyle2.visibility === "hidden") {
document.getElementById("number-spinner-down").style.visibility = "visible";
}
else {
if(countInput.value === "0") {
countInput.style.visibility = "hidden"
}
document.getElementById("number-spinner-down").style.visibility = "hidden";
}
},
I just started with vue.. please forgive my sloppyness
It is always better to keep jQuery away from Vue, since it is having its own functionalities to handle most of the requirements.
I'm not clear which div should set for toggle the view. So I added one link to toggle it. Hope this will help.
<div class="column asoebi-list-item" v-for="result in results.items">
<div id="item-event" class="columns is-mobile">
<div class="column auto has-text-left">
<p class="item-name">{{result.name}}</p>
<p class="item-price" id="item-price"> {{result.price}}</p>
<p class="item-units">{{result.amountAvailable}} Units Remaining · {{result.colour.name}}</p>
</div>
<div class="column is-2" v-show="result.active">
<button id="number-spinner-up" class="o-button button-bottom" type="button"
onclick="this.parentNode.querySelector('[type=number]').stepUp();">
+
</button>
<input id="count-input" type="number" name="number" min="0" max="900" v-model="result.count">
<button id="number-spinner-down" class="o-button button-top" type="button"
onclick="this.parentNode.querySelector('[type=number]').stepDown();">
-
</button>
</div>
toggle
</div>
</div>
Also, made some changes to the array results to handle the v-model and toggle functionality
data: () => {
return {
results: {
"items": [
{
"id": "770c257b-7ded-437c-99b5-3b8953b5be3a",
"name": "Gsbssbb",
"price": 9559,
"colour": {
"name": "Blue",
"hex": "FF0000AE"
},
"amountAvailable": 949,
"count": null,
"active": true
},
{
"id": "8ecc6558-0c16-4497-b742-5eb5cb28c572",
"name": "Vsbdbdb",
"price": 6559,
"colour": {
"name": "Purple",
"hex": "FF800080"
},
"amountAvailable": 6595,
"count": null,
"active": true
}
],
}
}
},
You are using Vue ! Do Not Focus On Operating The DOM ! You are not using jQuery ! Read Vue DOCs before coding !
I have a shopping cart from shopify. The object looks like this:
{
"attrs": {
"line_items": [
{
"image": {
"id": 19361216518,
"created_at": "2016-10-03T11:50:25-05:00",
"position": 1,
"updated_at": "2017-02-03T17:11:13-06:00",
"product_id": 8659646086,
"src": "https://cdn.shopify.com/s/files/1/1481/5646/products/watermain-box.jpg?v=1486163473",
"variant_ids": [
]
},
"image_variants": [
{
"name": "pico",
"dimension": "16x16",
"src": "https://cdn.shopify.com/s/files/1/1481/5646/products/watermain-box_pico.jpg?v=1486163473"
}
],
"variant_id": 30287712070,
"product_id": 8659646086,
"title": "Dome Water Main Shut Off Valve",
"quantity": 1,
"properties": {
},
"variant_title": "Default Title",
"price": "99.99",
"compare_at_price": null,
"grams": 0,
"shopify-buy-uuid": "shopify-buy.1494514993286.2"
}
],
"shopify-buy-uuid": "shopify-buy.1494514993286.1"
}
And a function that looks like this:
var updateCart = function() {
var cart = localStorage.getItem(domeCart).toJSON();
if (cart.lineItemCount != 0) {
var shoppingCart = document.getElementById('shopping-cart');
rivets.bind(shoppingCart,{cart:cart});
}
}
And a cart that looks like this:
<div id="shopping-cart">
<h3 class="empty-cart">Empty!</h3>
<div class="top-cart-items items">
<div class="top-cart-item clearfix">
<div class="top-cart-item-image">
<img src="images/shop/small/6.jpg" alt="Light Blue Denim Dress" />
</div>
<div class="top-cart-item-desc">
Light Blue Denim Dress
<span class="top-cart-item-price">$24.99</span>
<span class="top-cart-item-quantity">x 3</span>
</div>
</div>
</div>
<div class="top-cart-action clearfix">
<span class="fleft top-checkout-price">$114.95</span>
View Cart
</div>
</div>
I'm having trouble figuring out how I can use rivets to check if the object is empty or not and if it is empty put <h2>Shopping cart empty</h2> but if it isn't empty loop through all of the cart items and place the data in its respectable part of the markup.
I've looked through Rivets.js documentation and it the product doesn't seem well documented. Any help would be very much appreciated.
This is the format of json which I need to parse:
[{
"perAddress": {
"city": "Delhi",
"Street": "saket",
"pin": "101011"
},
"flag": false
}, {
"perAddress": {
"city": "Delhi",
"Street": "malvya",
"pin": "101011"
},
"flag": true,
"alterAddress": {
"city": "bangalore",
"street": "velondore",
"pin": "560103"
}
}];
If the flag is false then the corresponding row will not be
highlighted and only perAddress will be populated .
If the flag is true then the corresponding row will be highlighted with
containing perAddress and on click on the row the alterAddress need
to populated. How to iterate through the json?
I can tell you in 2 ways. No need of using flag too.
.highlight {
background-color: gray;
}
Using flag solution follows:
<div>
<div ng-repeat="address in addresses" ng-class="{'highlight' : address.flag}">
<a ng-if="!showAlterAddress" ng-click="showAlterAddress = !showAlterAddress">{{address.perAddress}}</a>
<span ng-if="showAlterAddress">{{address.alterAddress}}</span>
</div>
</div>
Without using flag solution follows:
<div>
<div ng-repeat="address in addresses" ng-class="{'highlight' : address.alterAddress}">
<a ng-if="!showAlterAddress" ng-click="showAlterAddress = !showAlterAddress">{{address.perAddress}}</a>
<span ng-if="showAlterAddress">{{address.alterAddress}}</span>
</div>
</div>
Try this
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.data = [{
"perAddress": {
"city": "Delhi",
"Street": "saket",
"pin": "101011"
},
"flag": false
}, {
"perAddress": {
"city": "Delhi",
"Street": "malvya",
"pin": "101011"
},
"flag": true,
"alterAddress": {
"city": "bangalore",
"street": "velondore",
"pin": "560103"
}
}];
});
.Highlight {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="d in data" ng-init="" ng-click="d.flag = !d.flag" ng-class="{'Highlight' : d.alterAddress}">
<li>{{d.perAddress}}
<div ng-if="d.alterAddress">
<div ng-if="!d.flag">{{d.alterAddress}}</div>
</div>
</li>
</div>
</div>
Create a css class "Highlight" and use this code -
<ul>
<li ng-repeat="i in jsonArray" ng-class="{'Highlight' : i.flag}">
<span>{{i.perAddress.city}} | {{i.perAddress.Street}} | {{i.perAddress.pin}}</span>
</li>
</ul>
Objective
Give each of the gifts a data-id of 1 all the way up to gifts.length (which is 245) that would then help me to pull the corresponding data from the array
Find a better way to repeat the structure .gift structure for all gifts in the array
Problem
I have an array of 200+ gifts all with a similar structure, I've been trying to give each gift a unique data-id, but instead I'm getting the last ID in the array, which is 245
I'm also wondering what the best way to repeat this structure without having to use something like handlebars.js, I've tried multiplyNode, but I'm not sure if the browser support is great vs. append
<div class="gift data-id="">
<img src="" data-original="" class="gift__image lazy">
<p class="gift__name">tk-name</p>
<p class="gift__price">tk-price</p>
<p class=""><span class="gift__description">tk-description</span> tk-url</p>
<div class="gift__share">
<div class="gift__icons">
<i class="fa fa-twitter" aria-hidden="true"></i>
<i class="fa fa-facebook" aria-hidden="true"></i>
<i class="fa fa-pinterest-p" aria-hidden="true"></i>
<i class="fa fa-envelope" aria-hidden="true"></i>
</div>
</div>
<button class="btn btn--buy">Buy on Amazon</button>
</div> <!-- .gift -->
scripts.js
// Loop over all of the gifts
for (let i = 0; i < gifts.length; i++) {
$(".gift").attr("data-id", [i]);
// Gift information from gifts.js
let giftName = $(".gift__name").html(gifts[i].Name);
let giftPrice = $(".gift__price").html(gifts[i].Price).prepend("$");
let giftDescription = $(".gift__description").html(gifts[i].Description);
let giftLink = $(".gift__link").html(gifts[i].URL);
}
function multiplyNode(node, count, deep) {
for (var i = 0, copy; i < count - 1; i++) {
copy = node.cloneNode(deep);
node.parentNode.insertBefore(copy, node);
}
}
const totalGifts = gifts.length
multiplyNode(document.querySelector('.gift'), totalGifts, true);
gifts.js (There are a total of 245 gifts)
var gifts = [
{
"ID": 1,
"Name": "Air plants",
"Price": 25,
"Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
"Category": "Gifts for anyone",
"Type": "Other",
"URL": "flowersandweeds.com",
"Destination": "Cherokee Street",
"Location": "Flowers and Weeds, 3201 Cherokee Street",
"Latitude": 38.59,
"Longitude": -90.2369742,
"Position": "38.5949207, -90.2369742",
"ImageURL": "-"
}
];
It looks to me that you're assigning each id (and replacing it) to all elements with the .gift class every time you go through the loop.
Try assigning it only tho the current gift:
var gift = $($(".gift")[i]);
gift.attr("data-id", [i]);
This might not be the way you want to do it, but if I was doing this, I would do it kind of like this:
var gifts = [{
"ID": 1,
"Name": "1 Air plants",
"Price": 400,
"Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
"Category": "Gifts for anyone",
"Type": "Other",
"URL": "flowersandweeds.com",
"Destination": "Cherokee Street",
"Location": "Flowers and Weeds, 3201 Cherokee Street",
"Latitude": 38.59,
"Longitude": -90.2369742,
"Position": "38.5949207, -90.2369742",
"ImageURL": "-"
}, {
"ID": 2,
"Name": "2 Dandilions",
"Price": 12,
"Description": "Some explaination here.....",
"Category": "Gifts for anyone",
"Type": "Other",
"URL": "flowersandweeds.com",
"Destination": "Cherokee Street",
"Location": "Flowers and Weeds, 3201 Cherokee Street",
"Latitude": 38.59,
"Longitude": -90.2369742,
"Position": "38.5949207, -90.2369742",
"ImageURL": "-"
}, {
"ID": 3,
"Name": "3 Air plants",
"Price": 6662,
"Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
"Category": "Gifts for anyone",
"Type": "Other",
"URL": "flowersandweeds.com",
"Destination": "Cherokee Street",
"Location": "Flowers and Weeds, 3201 Cherokee Street",
"Latitude": 38.59,
"Longitude": -90.2369742,
"Position": "38.5949207, -90.2369742",
"ImageURL": "-"
}, {
"ID": 4,
"Name": "4 Air plants",
"Price": 2325,
"Description": "A small glass globe containing air plants, gravel, moss and crystals, comes in various designs and can brighten up your window or desk ($25) at Flowers and Weeds, 3201 Cherokee Street, flowersandweeds.com, which also sells monthly subscription boxes at various price points.",
"Category": "Gifts for anyone",
"Type": "Other",
"URL": "flowersandweeds.com",
"Destination": "Cherokee Street",
"Location": "Flowers and Weeds, 3201 Cherokee Street",
"Latitude": 38.59,
"Longitude": -90.2369742,
"Position": "38.5949207, -90.2369742",
"ImageURL": "-"
}];
// Loop over all of the gifts
for (var i = 0; i < gifts.length; i++) {
// Gift information from gifts.js
// -------------------------------------------------------------
// This is how I would do it. This way is really easy to set up.
// ------------------------------------------------------------
var id = i;
var giftName = gifts[i].Name;
var giftPrice = "$" + gifts[i].Price;
var giftDescription = gifts[i].Description;
var giftLink = gifts[i].URL;
var dataBlock = "<div class='gift' data-id='" + i + "'>\
<img src='' data-original='' class='gift__image lazy'>\
<p class='gift__name'>" + giftName + "</p>\
<p class='gift__price'>" + giftPrice + "</p>\
<p class=''><span class='gift__description'>" + giftDescription + "</span> <a href='' class='gift__link'>" + giftLink + "</a>\
</p>\
<div class='gift__share'>\
<div class='gift__icons'>\
<a href='#' class='link--twitter' target='_blank'>\
<i class='fa fa-twitter' aria-hidden='true'></i>\
</a>\
<a href='#' class='link--facebook' target='_blank'>\
<i class='fa fa-facebook' aria-hidden='true'></i>\
</a>\
<a href='#' class='link--pinterest' target='_blank'>\
<i class='fa fa-pinterest-p' aria-hidden='true'></i>\
</a>\
<a href='#' target='_blank'>\
<i class='fa fa-envelope' aria-hidden='true'></i>\
</a>\
</div>\
</div>\
<a href='#' target='_blank'>\
<button class='btn btn--buy'>Buy on Amazon</button>\
</a>\
</div>";
// ---------------------------------------------------
// append to the contents
// ---------------------------------------------------
$("#contents").append(dataBlock);
}
.gift {
background: #22252b;
padding: 20px;
margin-bottom: 10px;
color: #FFF;
}
.gift__link {
text-decoration: none;
color: deepskyblue;
}
.gift__icons i {
font-size: 20px;
margin: 5px;
}
.gift__icons a {
text-decoration: none;
color: #FFF;
float: right;
}
.gift__icons a:hover {
opacity: 0.7;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://use.fontawesome.com/b64737b88c.js"></script>
<div id="contents"></div>
I'm developing a page where I need to show some boxes (using ng-repeat) that contains info of channels and where it will be shown (which are cities).
The problem I am facing is when I repeat the second ng-repeat:
<table class="table table-condensed" ng-init="nitsCh = [objsCh[$index].nit]">
This should get the $index of first ng-repeat and create a new array with the places the channels will be shown. And it does exactly that. But, when I apply the second ng-repeat using this array, it doesn't work properly.
Said that my html looks like this (PS: I need to use the index value instead of objCh.name because I place these boxes into columns)
<div class="box box-solid box-default" ng-repeat="(indexO, objCh) in objsCh track by indexO" ng-if="indexO%4==0 && indexO<=10">
<div class="box-header">
<div class="pull-left">
<img src="dist/img/channels/{{ objsCh[indexO].pic }}" data-toggle="tooltip" title="" data-original-title="Alterar logo do canal">
<h3 class="box-title">{{ objsCh[(indexO)].name }}</h3>
</div>
<div class="box-tools pull-right">
<button class="btn btn-box-tool" data-toggle="tooltip" title="" data-original-title="Adicionar ou Remover NIT"><i class="fa fa-plus"></i></button>
</div>
</div>
<div class="box-body">
<table class="table table-condensed" ng-init="nitsCh = [objsCh[indexO].nit]">
<tbody>
<tr>
<th style="width: 10px">#</th>
<th>Nit</th>
</tr>
<tr ng-repeat="(indexN,nitCh) in nitsCh track by indexN">
<td>{{ objsCh[(indexO + 1)].nit[indexN].num }}</td>
<td>{{ objsCh[(indexO + 1)].nit[indexN].name }}</td>
</tr>
</tbody>
</table>
</div>
</div>
The JS file looks like this:
var app = angular.module('appApp', []);
app.controller('ctrlApp', function($scope, $http) {
var url = "includes/exibChNit.php";
$http.get(url).success(function(response) {
all = response;
$scope.objsCh = all.channels;
});
});
And the json file (that php create) looks like this:
{
"channels": [{
"id": "1",
"sid": "1",
"name": "Channel",
"pic": "channel.jpg",
"crc32": "A1g423423B2",
"special": "0",
"url": "",
"key": "",
"type": "",
"city": [{
"num": "1",
"name": "S�o Paulo"
}, {
"num": "2",
"name": "Rio de Janeiro"
}]
}, {
"id": "2",
"sid": "2",
"name": "CHannel 1",
"pic": "channel.jpg",
"crc32": "A1F5534234B2",
"special": "0",
"url": "",
"key": "",
"type": "",
"city": [{
"num": "1",
"name": "S�o Paulo"
}, {
"num": "2",
"name": "Rio de Janeiro"
}]
}]
}
When I try this it works:
<table class="table table-condensed" ng-init="nitsCh = [objsCh[($parent.$index + 1)].nit]">
But I can't make it this way because the json nodes will be dynamic.
Thanks in advance!
ng-repeat's create their own $scope.
So, for the inner ng-repeats, you have access to $parent.$index, where $parent is the parent scope of the current repeat block.
For ex:
<ul ng-repeat="section in sections">
<li>
{{section.name}}
</li>
<ul>
<li ng-click="loadFromMenu($parent.$index)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>
Plunkr http://plnkr.co/edit/hOfAldNevxKzZQlxFfBn?p=preview
(simplified from this answer passing 2 $index values within nested ng-repeat)