how to create elements dynamically in HTML using JSON file - javascript

I want to create HTML elements dynamically using JSON file.
{"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
This is my JSON file. i want to create HTML buttons dynamically. Buttons should be create like JAVA,C#,C++. if i add something next to C++ then that button should get created dynamically

You can try something like this FIDDLE
however, i changed the myObject to an array of json objects as follows:
var jsonObj = {"myObject":
[
{
title: 'JAVA',
id: "JAVAsubj",
path: "json/data.json"
},
{
title: "C#",
id: "JAVAsubj",
path: "json/data1.json"
},
{
title: "C++",
id: "JAVAsubj",
path: "json/data2.json"
}
]
}
var count = Object.keys(jsonObj.myObject).length;
var container= document.getElementById('buttons'); // reference to containing elm
for(var i=0;i<count;i++){
var obj= jsonObj.myObject[i];
var button = "<input type='button' value="+obj.title+"></input>"
container.innerHTML+=button;
}

First thing you need to do that get your JSON into js object :
var myJSON= {"myObject": {
"JAVA": {
"id": "JAVAsubj",
"path": "json/data.json"
},
"C#": {
"id": "JAVAsubj",
"path": "json/data1.json"
},
"C++": {
"id": "JAVAsubj",
"path": "json/data2.json"
}
}
}
now get the value of your object into dictionary like below :
var dctLanguages = myJSON["myObject"];
now to render buttons dynamically, just do this :
var strHTML = '';
for (var key in dctLanguages)
{
var language = dctLanguages[key];
strHTML += '<input type="button" id="'+language.id+'" value="'+key+'"/>';
}
and append this HTML into your container div as follows :
$(strHTML).appendTo("#container");
Hope this will work for you..

const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})

This shoule help you
const info = [
{
"id": 1,
"img": "a.jpg",
"name": "Avinash Mehta",
"desc": "I am Web Developer"
},
{
"id": 2,
"img": "c.jpg",
"name": "Avinash",
"desc": "I am Web"
},
{
"id": 3,
"img": "b.jpg",
"name": "Mehta",
"desc": "I am Developer"
},
]
const main = document.querySelector(".main");
window.addEventListener("DOMContentLoaded", function(){
let displayInfo = info.map(function(profile){
return` <div class="profile">
<img src="${profile.img}" alt="">
<h2>${profile.name}</h2>
<p>${profile.desc}</p>
</div>`
});
displayInfo = displayInfo.join("");
main.innerHTML = displayInfo
})

Related

How to filter an objects where is employeeId equals to some value

I'm using knockoutjs, but the question is really in Javascript domain.
I have variable vm.filteredSerivces() which contains all services by all employees.
Now, I want to just preserve those filteredSerivces where is vm.filteredSerivces()[0].GroupedServices[x].EmployeeId == 3684 (x is the number of index number of each object in GroupedServices object list)
I tried as follows:
var filteredSrvcs = vm.filteredSerivces()[0].GroupedServices.filter(x => x.EmployeeId != Id).remove();
vm.filteredSerivces(filteredSrvcs );
But I changed structure in that way, and my bindings in html is not corresponding.
Is there any other way to just remove this sub-sub object, and to preserve a structure as it is?
Here is the
Here's an example that maps a new array of new objects and the filter is set to only include the GroupedServices items where Id == 2000
let res = data.map(({ServiceTypeName, GroupedServices}) =>{
GroupedServices= GroupedServices.filter(({Id}) => Id == 2000);
return {ServiceTypeName,GroupedServices }
})
console.log(res)
<script>
let data =
[
{
"ServiceTypeName": "Type 1",
"GroupedServices": [{
"Id": 1,
"Name": "A"
}, {
"Id": 2,
"Name": "A"
},
{
"Id": 28456,
"Name": "AGSADGJS"
}]
},
{
"ServiceTypeName": "Type 2",
"GroupedServices": [{
"Id": 1203,
"Name": "AHASJ"
}, {
"Id": 2000,
"Name": "AHSJD"
},
{
"Id": 284536,
"Name": "UEHNCK"
}]
}];
</script>

How click to open popup Organisational Chart Plugin With jQuery

this is tree view on my website based on jquery org chart plugin, this tree created dynamically and also create children.
code is :
$(function() {
var datascource = {
'name': 'Kirby Cochran',
'title': '5061',
'children': [
{
"name": "Sharon Edwards",
"title": "11454",
"children": [
{
"name": "Kirby Cochran",
"title": "5061-kr",
"children": [
{
"name": "Michael Wach",
"title": "5063"
}
]
},
{
"name": "Phil Ungricht",
"title": "6189",
"children": [
{
"name": "Elaine 2 Cochran",
"title": "10238"
}
]
},
{
"name": "Roberto Montero",
"title": "5371"
}
]}]};
var oc = $('#chart-container').orgchart({
'data' : datascource,
'nodeContent': 'title',
'draggable': true,
'dropCriteria': function($draggedNode, $dragZone, $dropZone) {
if($draggedNode.find('.content').text().indexOf('manager') > -1 && $dropZone.find('.content').text().indexOf('engineer') > -1) {
return false;
}
return true;
}
});
oc.$chart.on('nodedropped.orgchart', function(event) {
console.log('draggedNode:' + event.draggedNode.children('.title').text()
+ ', dragZone:' + event.dragZone.children('.title').text()
+ ', dropZone:' + event.dropZone.children('.title').text()
);
});});
here requirement is if clicked any boxes open the popup and show details of customers. org chart
Here is some code snippet to load a pop-up
$(.node).click(function(){
var id = $(this).attr('id');
// use ajax here and getdata using id then display a modal and populate it
});

Nesting Json Data with jquery

I have this data from a csv file that i have to use in a dependant dropdown with jquery. I can't figure out if it is possible to nest the data i received for what i already have coded.
CSV file
Banco Tarjeta Cuotas Medio_Pago Coeficiente TEA CFT
Santander Visa 1 modulodepago2 1 0.00% 0.00%
Santander Visa 1 nps 1.0262 18.56% 22.84%
Frances Visa 1 modulodepago2 1 0.00% 0.00%
Frances Master 2 nps 1.0262 18.56% 22.84%
My json data comes like this
[{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"modulodepago2",
"coeficiente":"1","tea":"0.00%","cft":"0.00%"},
{"banco":"Santander","tarjeta":"Visa","cuotas":"1","medio_pago":"nps",
"coeficiente":"1.0262","tea":"18.56%","cft":"22.84%"} ...
etc...
Is there a way i can nest this json data like this (+ adding unique names and id's)?
var myJson = {
"banco": [
{
"name": "Santander",
"id": "Santander",
"tarjeta": [
{
"name": "Visa",
"id": "SantanderVisa",
"cuotas": [
{
"name": "1",
"id": "SantanderVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
},
{
"name": "1",
"id": "SantanderVisa2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
},
{
"name": "Frances",
"id": "Frances",
"tarjeta": [
{
"name": "Visa",
"id": "FrancesVisa",
"cuotas": [
{
"name": "1",
"id": "FrancesVisa1",
"medio_pago": "modulodepago2"
"coeficiente": "1",
"tea": "0.00%",
"cft": "0.00%",
}
]
},
{
"name": "Master",
"id": "FrancesMaster",
"cuotas": [
{
"name": "2",
"id": "FrancesMaster2",
"medio_pago": "nps"
"coeficiente": "1.0262",
"tea": "18.56%",
"cft": "22.84%",
}
]
}
]
}
]
}
You will need to group by keys. An easy way to do this is to use Lodash or Underscore.js.
I used Papa Parse to convert the CSV data into JSON.
var csvData = $('#csv-data').text().trim();
var jsonData = Papa.parse(csvData, { delimiter:',', header:true }).data;
var transformedJson = {
banco : _.chain(jsonData)
.groupBy('Banco')
.toPairs()
.map(banco => {
return {
name : banco[0],
id: banco[0],
tarjeta : _.chain(banco[1])
.groupBy('Tarjeta')
.toPairs()
.map(tarjeta => {
return {
name: tarjeta[0],
id: banco[0] + tarjeta[0],
cuotas: _.map(tarjeta[1], cuota => {
return {
name: cuota['Cuotas'],
id: banco[0] + tarjeta[0] + cuota['Cuotas'],
medio_pago: cuota['Medio_Pago'],
coeficiente: cuota['Coeficiente'],
tea: cuota['TEA'],
cft: cuota['CFT']
}
})
};
})
}
}).value()
}
console.log(JSON.stringify(transformedJson, null, 2));
.as-console-wrapper { top: 0; max-height: 100% !important; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.4/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
<textarea id="csv-data" style="display:none" rows="5" cols="72">
Banco,Tarjeta,Cuotas,Medio_Pago,Coeficiente,TEA,CFT
Santander,Visa,1,modulodepago2,1,0.00%,0.00%
Santander,Visa,1,nps,1.0262,18.56%,22.84%
Frances,Visa,1,modulodepago2,1,0.00%,0.00%
Frances,Master,2,nps,1.0262,18.56%,22.84%
</textarea>
try something like this
you get all medio_pago for the others objects you just use the object name.
I haven't tested it but I'm sure this will work for you.
var Json = ...
$.each(Json, function(i, item) {
alert(myJson[i].banco.tarjeta.cuotas.medio_pago);
});

filter result using 2 JSON

This is my saved localstorage,
[{"industry_Id":1,"merchant_id":2}]
I want to filter below result, to get HP.
{
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
}
I thought of using multiple $.each but it have to iterate few times and it's quite redundant.
I would prefer using Javascript for loop, that way you can skip iterating over every object once required element is found.
Without jQuery (using for)
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
With jQuery (using $.each)
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
var arg = [{"industry_Id":1,"merchant_id":2}];
var data = {
"industries": [
{
"id": 1,
"name": "oil and gas",
"merchant": [
{
"id": 1,
"name": "ABC",
},
{
"id": 2,
"name": "DEF",
},
{
"id": 3,
"name": "GHJ",
}
]
},
{
"id": 2,
"name": "IT",
"merchant": [
{
"id": 1,
"name": "Apple",
},
{
"id": 2,
"name": "HP",
},
{
"id": 3,
"name": "Google",
}
]
}
]
};
var i, j, merchant = null;
for(i = 0; i < data['industries'].length; i++){
if(data['industries'][i]['id'] == arg[0]['industry_Id']){
for(j = 0; j < data['industries'][i]['merchant'].length; j++){
if(data['industries'][i]['merchant'][j]['id'] == arg[0]['merchant_id']){
merchant = data['industries'][i]['merchant'][j];
break;
}
}
if(merchant !== null){ break; }
}
}
console.log(merchant);
document.writeln("<b>Without jQuery:</b><br>");
document.writeln((merchant !== null) ? "Found " + merchant['name'] : "Not found");
var merchant_found = null;
$.each(data['industries'], function(i, industry){
if(industry['id'] == arg[0]['industry_Id']){
$.each(industry['merchant'], function(i, merchant){
if(merchant['id'] == arg[0]['merchant_id']){
merchant_found = merchant;
}
return (!merchant_found);
});
}
return (!merchant_found);
});
console.log(merchant_found);
document.writeln("<br><br><b>With jQuery:</b><br>");
document.writeln((merchant_found) ? "Found " + merchant_found['name'] : "Not found");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
selectors.map(function(selector) {
return data.industries.filter(function(industry) {
return industry.id == selector.industry_Id;
})[0].merchant.filter(function(merchant) {
return merchant.id == selector.merchant_id;
})[0].name;
});
// => DEF
If you want "HP", you want industry 2, not industry 1.
.filter(...)[0] is not really optimal. You could use .find(...), but that is not yet universally supported. Or you could use plain old JavaScript and write for loops instead to make it fast. Or you could use objects with ID keys instead of arrays to make lookups faster.
When it comes into a position where collection of data is what you're processing, I suggest you to take a look at underscore.js. It's not optimal choice for the best performance but it does make you code more readable and makes more sense especially when compared with loop.
Say data is a variable which stores your JSON data.
Try this:
// Given this selector criteria
var select = [{"industry_Id":1,"merchant_id":2}];
function filterByCriteria(criteria, data){
var match = [];
_.each(criteria, function(crit){
function matchIndustry(rec){ return rec.id===crit.industry_Id }
function matchMerchant(rec){ return rec.id===crit.merchant_id }
// Filter by industry id
var industry = _.first(_.where(data.industry, matchIndustry));
// Filter by merchant id
var merchant = _.where(industry.merchant, matchMerchant);
_.each(merchant, function addToMatchResult(m){
match.push(m.name);
});
});
return match;
}
var filteredData = filterByCriteria(select, data);
From snippet above, any merchants which match the search criteria will be taken to the match list. Is it more readable to you?
Do you even need numerical id's? Gets super easy when you don't.
/*
{
"industry": {
"oil and gas":{
"merchant": {
"ABC": {
"name": "ABC oil"
},
"DEF": {
"name": "DEF gas"
},
"GHJ" :{
"name": "GHJ oil and gas"
}
}
},
"IT": {
"merchant": {
"Apple" : {
"name": "Apple computers"
},
"HP": {
"name": "Hewlett Packard"
},
"Google": {
"name": "Google. Maw haw haw"
}
}
}
}
}
*/
var data = '{"industry": {"oil and gas":{"merchant": {"ABC": {"name": "ABC oil"},"DEF": {"name": "DEF gas"},"GHJ" :{"name": "GHJ oil and gas"}}},"IT": {"merchant": {"Apple" : {"name": "Apple computers"},"HP": {"name": "Hewlett Packard"},"Google": {"name": "Google. Maw haw haw"}}}}}';
data = JSON.parse(data);
var merchant = data.industry['IT'].merchant['HP'];
alert(merchant.name);
//console.log(merchant.name);

Angular Select. Add element and automatically select it

Look ex. jsfiddle example
HTML
<div ng-app="app" ng-controller="mCtrl">
<select size="20" ng-model="selectedType" ng-init="selectedType=types[0]"
ng-options="type.name for type in types">
</select>
<button ng-click="addElem()">add elem in array</button>
</div>
Controller
$scope.types = [ my Array of objects ];
$scope.addElem = function() {
element = {
"id": 999,
"name": "xxx"
};
$scope.types.push(element);
}
I want to add element in ng-options array, and automatically select it in select Box with model changing.
I tried
$scope.selectedType = $scope.types[$scope.types.lenght - 1]
, but it doesn't work.
You have misspelled length.
Here is solution which works:
app = angular.module('app', []);
app.controller('mCtrl', function($scope) {
$scope.types = [
{
"id": 0,
"name": "Zaj"
},
{
"id": 1,
"name": "Emoltra"
},
{
"id": 2,
"name": "Malathion"
},
{
"id": 3,
"name": "Pyramax"
},
{
"id": 4,
"name": "Boink"
},
{
"id": 5,
"name": "Savvy"
},
{
"id": 6,
"name": "Accruex"
},
{
"id": 7,
"name": "Zappix"
}
];
$scope.addElem = function() {
element = {
"id": 7,
"name": "Zappix"
};
$scope.types.push(element);
$scope.selectedType = $scope.types[$scope.types.length - 1];
}
})
DEMO
In your code, there is a typo you have misspelled length
$scope.selectedType = $scope.types[$scope.types.length- 1]
DEMO
OR
You can set it using $scope.selectedType = element
$scope.addElem = function () {
element = {
"id": $scope.types.length + 1,
"name": "Zappix" + $scope.types.length + 1
};
$scope.types.push(element);
$scope.selectedType = element;
}
DEMO

Categories

Resources