Hi i wanna display some values of an object,
the object has the next structure:
{
0:
{ id: "value",
topic: "value",
description: "value",
...
}
1:
{
...
}
}
and this is my code for display in a table with id=cursos
it has an ajax call before so I do this inside .done() method
the thing is that when I use double each to call teh first object and display its attributes it doesn't show anything, but when I call them by its name, without $.each() it is showed in table format,
How can I show the values of my objects in table format using $.each(), just to save code lines note: i have also changed the .html() for .append() and it's the same result.
resultado.done(
function (data){//success
$("#cursos").append($("<tr>").append(
$("<td>").append("Tema"),
$("<td>").append("Indice"),
$("<td>").append("DescripciĆ³n"),
$("<td>").append("Fecha"),
$("<td>").append("Idioma"),
$("<td>").append("Imagen"),
$("<td>").append("Enlaces"),
$("<td>").append("Nivel"),
$("<td>").append("Palabras clave"),
$("<td>").append("Autor"),
$("<td>").append("Escuela"),
$("<td>").append("Categoria"),
$("<td>").append("Subcategoria")
),
$("<tr>").html(
$.each(data, function (key, data1) {
$.each(data1, function (index, datos) {
console.log("index", datos);
$("<td>").append(datos);
})
})
/* if this block comment is removed it works
$("<td>").append(data[0].tema),
$("<td>").append(data[0].indice),
$("<td>").append(data[0].descripcion),
$("<td>").append(data[0].fecha),
$("<td>").append(data[0].idioma),
$("<td>").append(data[0].imagen),
$("<td>").append(data[0].enlaces),
$("<td>").append(data[0].nivel),
$("<td>").append(data[0].keywords),
$("<td>").append(data[0].autorId),
$("<td>").append(data[0].escuelasId),
$("<td>").append(data[0].categoriaId),
$("<td>").append(data[0].subcategoriaId)*/
)
);
//data[0].tema
}//function DONE
);//done
Try something like this:
var dataCollection = {
0: {
id: "id0",
topic: "topic0",
description: "desc0"
},
1: {
id: "id1",
topic: "topic1",
description: "desc1"
},
2: {
id: "id2",
topic: "topic2",
description: "desc2"
}
};
$.each(dataCollection, function(index) {
$("table#cursos").append("<tr>");
$.each(dataCollection[index], function(key, value) {
$("table#cursos").append("<td>" + value + "</td>");
});
$("table#cursos").append("</tr>");
});
See fiddle.
Hope this helps!
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<!--http://stackoverflow.com/a/8563020/3200163-->
<!--http://stackoverflow.com/questions/8562744/how-to-loop-through-this-nested-object-json-array-and-build-an-html-string-with-->
</head>
<body>
<script type="text/javascript" src="scripts/jquery.js"></script>
<script>
var data = {
"sEcho": 1,
"total": "1710",
"aaData": [
[
"Help",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76fab1e95bd.mp3?King_of_Spain_Entropy_02_Animals_Part_1.mp3",
"1784",
"3",
0,
null,
"0000-00-00 00:00:00"
],
[
"A Day In The Life",
"http:\/\/www.mysite.com\/wp-content\/uploads\/2011\/09\/dt_intfc4e732d1f1276d_4e76f5fc253a1.mp3?JenWood_Zeppelin.mp3",
"3573",
"3",
0,
null,
"0000-00-00 00:00:00"
]
]
}
var str = "";
for (var item in data.aaData) {
str += '<tr>';
for (idata in data.aaData[item]) {
str += '<td>' + data.aaData[item][idata] + '</td>';
}
str += '</tr>';
}
$('body').append("<table>" + str + "</table>");
</script>
</body>
</html>
This code creates a table correctly :)
Related
I Have a Simple JSON File With Data and I want to display that data in HTML website following is the JSON file :
[
{
Indice_Name: 'Nasdaq',
price: '13,017.79',
change: '+40.12 (+0.31%)'
},
{
'Indice_Name Name': 'FTSE',
price: '6,729.69',
'change%': '+54.86 (+0.82%)'
},
{
'Indice_Name Name': 'Dow_Jones',
price: '32,787.33',
'change%': '+167.85 (+0.51%)'
},
{
'Indice_Name Name': 'SGX_Nifty',
price: '9.91',
'change%': '-0.02 (-0.20%)'
},
{
'Indice_Name Name': 'Nikkei_225',
price: '29,176.70',
'change%': '+446.82 (+1.56%)'
}
]
Following is My HTML and Javascript File:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="World_Indice_DataDiv"></div>
<script>
fetch('http://127.0.0.1:5500/data/World_Indices_Display.json')
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log(err);
});
function appendData(data) {
var mainContainer = document.getElementById("World_Indice_DataDiv");
for (var i = 0; i < data.length; i++) {
var div = document.createElement("div");
div.innerHTML = 'Indice Name: ' + data[i].Indice_Name + '\n' + 'Price : ' + data[i].price + '\n' + data[i].change;
mainContainer.appendChild(div);
}
}
</script>
</body>
</html>
When i run this Following piece of code it doesnt show me the expected results:
How Can I Display The JSON Data Correctly?
Your JSON structure is not how it should be. If the first object is how it should be (judging by the fact that they are displayed correctly), the others should have the same property names.
In fact, the other objects (except the first one) all have a property called 'Indice_Name Name' but it should be 'Indice_Name'. They also have another property called "change%" when it should be "change" to match the first object.
You need to change the JSON file to this (the rest should follow the same structure):
[
{
"Indice_Name": "Nasdaq",
"price": "13,017.79",
"change": "+40.12 (+0.31%)"
},
{
"Indice_Name": "FTSE",
"price": "6,729.69",
"change": "+54.86 (+0.82%)"
},
.
.
.
]
There's one issue with your json array if you check the first item has by key Indice_Name and the rest are Indice_Name Name, so if this is your response you can handle it like this:
const arr = [
{
"Indice_Name": "Nasdaq", // <--- here's one of your problems with response
"price": "13,017.79",
"change": "+40.12 (+0.31%)"
},
{
"Indice_Name Name": "FTSE", // <--- and here, idk why you receive these
"price": "6,729.69",
"change%": "+54.86 (+0.82%)" // <--- you can access these keys with
// brackets operator obj['key'] in this
// case you must write item['change%']
// to get value. Not recommended 2 have
// such weird names as keys!
},
{
"Indice_Name Name": "Dow_Jones",
"price": "32,787.33",
"change%": "+167.85 (+0.51%)"
},
{
"Indice_Name Name": "SGX_Nifty",
"price": "9.91",
"change%": "-0.02 (-0.20%)"
},
{
"Indice_Name Name": "Nikkei_225",
"price": "29,176.70",
"change%": "+446.82 (+1.56%)"
}
];
const div = document.getElementById('inner');
arr.forEach(item => {
// you can use backticks to make it easier
// since you're innering html you can use html tags to help you when
// displaying data!
div.innerHTML = `${div.innerHTML}
<p>Indice Name: ${item['Indice_Name'] || item['Indice_Name Name']}
<p>Price: ${item.price}</p>
<p>Change: ${item['change%']}</p>
<br>`
});
<div id="inner"></div>
I am now able to solve my problem,After looking at many answers on this question.Essentially the problem was that the keys of the JSON file were wrong and not similar to the first key of JSON file.After i fixed the JSON file the code started working properly.Hope this will help someone in future.
Correct JSON File:
[
{
Indice_Name: 'Nasdaq',
'price': '13,017.79',
'change': '+40.12 (+0.31%)'
},
{
'Indice_Name': 'FTSE',
'price': '6,729.69',
'change': '+54.86 (+0.82%)'
},
{
'Indice_Name Name': 'Dow_Jones',
'price': '32,787.33',
'change': '+167.85 (+0.51%)'
},
{
'Indice_Name': 'SGX_Nifty',
'price': '9.91',
'change': '-0.02 (-0.20%)'
},
{
'Indice_Name': 'Nikkei_225',
'price': '29,176.70',
'change': '+446.82 (+1.56%)'
}
]
I want to highlight the kendo grid cell by matching an external string text.
I googled a lot but found only searching a string in a particular column.
below is the code which works for one column
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName" },
{ field: "category" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
var grid = $("#grid").data('kendoGrid');
var value = 'te';
var regex = new RegExp(value, "gi");
var colIndex = 0;
grid.tbody.find('tr[data-uid]').each(function () {
var td = $(this).find('td:eq(' + colIndex + ')');
var item = grid.dataItem(this);
td.html(item.productName.replace(regex, '<span style="background-color:yellow">' + value + '</span>'));
});
But I want the search the string text across all columns.
Can anyone help me on this?
The best for doing that IMO is to use templates, e.g.:
template: "#= findText(data.fieldName) #"
The template will use a function to create the search highlight which can be something similiar as you already done:
var findText = function findText(text) {
let index = text.indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(value, "gi");
result = result.replace(regex, '<span style="background-color:yellow">' + value + '</span>');
}
return result;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.common.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.rtl.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.default.min.css">
<link rel="stylesheet" href="https://kendo.cdn.telerik.com/2019.3.1023/styles/kendo.mobile.all.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/angular.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/jszip.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2019.3.1023/js/kendo.all.min.js"></script></head>
<body>
<div id="grid"></div>
<script>
var value = 'co';
var findText = function findText(text) {
let index = text.toLowerCase().indexOf(value),
result = text;
// If substring is found in current text
if (index > -1) {
let regex = new RegExp(`(${value})`, "gi");
result = result.replace(regex, '<span style="background-color:yellow">$1</span>');
}
return result;
};
$("#grid").kendoGrid({
selectable: "multiple cell",
allowCopy: true,
columns: [
{ field: "productName", template: "#= findText(data.productName) #" },
{ field: "category", template: "#= findText(data.category) #" }
],
dataSource: [
{ productName: "Tea", category: "Beverages" },
{ productName: "Coffeete", category: "Beverageste" },
{ productName: "Ham", category: "Foodte" },
{ productName: "Bread", category: "Food" }
]
});
</script>
</body>
</html>
Demo in Dojo
I try actually to create a Simple Div Constrct based on a JS Array...
Unfortunately my Way below just shows up the Last Group / Element of the Array, what must be changed to create a repeating Div Construct for each Array Element?
Generated REsult should be like:
<div id="accordion">
<h3>'val.labelfromelement1'</h3>
<div class="notimportant">'val.Namefromelement1'</div>
<h3>'val.labelfromelement2'</h3>
<div class="notimportant">'val.Namefromelement2'</div>
<h3>'val.labelfromelement3'</h3>
<div class="notimportant">'val.Namefromelement3'</div>
<h3>'val.labelfromelement4'</h3>
<div class="notimportant">'val.Namefromelement4'</div>
</div>
Here is my actual Code:
var myData = [
{
label: "erster",
id: 0,
Name:"Ein Name"
},
{
label: "zweiter",
id: 1,
Name:"Der zweite Name"
},
{
label: "dritter",
id: 2,
Name:"Dritter Name"
}
]
$(document).ready(function(e) {
$.each(myData, function (i, val) {
myAccordion = "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="myAccordionDiv">
</div>
</body>
as you can see, it should result in an accordion that will be automatic increase if a we create a new element in the array (The Array is from a chart)
Any Suggestion? Thank you for your help!
The reason you only see the last one is because you never initialize the variable myAccordionDiv and append each html string in the iterations to it.
Fiddle: http://jsfiddle.net/hz0b6k71/
var myAccordion = "";
$.each(myData, function (i, val) {
myAccordion += "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
Your code is good but you have to append all the content of array to"myAccordion" var.
If you change your js code like this it will work.
$(document).ready(function(e) {
var myAccordion;
$.each(myData, function (i, val) {
myAccordion += "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
});
$("#myAccordionDiv").html(myAccordion);
});
I hope that will help you
Try appending variable myAccordion to #myAccordianDiv element within $.each()
var myData = [{
label: "erster",
id: 0,
Name: "Ein Name"
}, {
label: "zweiter",
id: 1,
Name: "Der zweite Name"
}, {
label: "dritter",
id: 2,
Name: "Dritter Name"
}
];
$(document).ready(function(e) {
$.each(myData, function(i, val) {
var myAccordion = "<h3>" + val.label + "</h3><div>" + val.Name + "</div>";
// append `myAccordion` string to `#myAccordionDiv`
$("#myAccordionDiv").append(myAccordion);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div id="myAccordionDiv">
</div>
</body>
Here's an approach with raw javascript:
http://jsbin.com/nofiqiweri/edit?html,js,console,output
you were not storing the data into the myAccordion variable properly.
var myData = [
{
label: "erster",
id: 0,
Name:"Ein Name"
},
{
label: "zweiter",
id: 1,
Name:"Der zweite Name"
},
{
label: "dritter",
id: 2,
Name:"Dritter Name"
}
];
var myAccordion;
for (var i=0; i<myData.length; i++) {
myAccordion += '<h3>'+myData[i].label+'</h3><div>'+myData[i].Name+'</div>';
}
document.getElementById('myAccordionDiv').innerHTML(myAccordion);
Bts something like that, could get it run in those few minuts: :/ But look for AngularJS and fill an Object or even better JSON-Object into a table.
Some good Tutorials for this:
http://www.w3schools.com/angular/angular_tables.asp
http://jsfiddle.net/mjaric/pj5br/
var myData = [{
label: "erster",
id: 0,
Name: "Ein Name"
}, {
label: "zweiter",
id: 1,
Name: "Der zweite Name"
}, {
label: "dritter",
id: 2,
Name: "Dritter Name"
}
]
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$scope.names = myData;);
});
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>BlaBlaBla</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div ng-controller="customersCtrl">
<div ng-repeat="x in names">
<h3>{{x.Name}}</h3>
</div>
</div>
</body>
</html>
I am trying to reformat a dynamically created JSON output into a format that can be consumed by the x-editable select type source[]. I need help building the array so that the re-formated JSON output looks like this:
{value: 2, name: 'Maintenance'},
Below is a sample original JSON which I am consuming:
{"COLUMNS":["SECTIONCOMMONNAME"],"DATA":[["Aircraft Overview"],["Email Server Settings"],["Maintenance"],["Page Sections"],["WOW"]]}
The code I am using is:
$(document).ready(function () {
var myURL = 'https://api.myjson.com/bins/3nzdj';
var myarray = [];
$.ajax({
url: myURL,
dataType: 'json',
success: function (e) {
console.log('My created console output:' +'<br>');
$.each(e.DATA, function (i, jsonDataElem) {
console.log("{value: " + i + ', ' + "name: " + '"'+this+"'}");
var item = {
"value": i,
"name": this
};
myarray.push(item);
});
var newJson = JSON.stringify(myarray);
console.log('My stringify output:' +'<br>' +newJson);
}
});
$('.sectionsAvailable').editable({
name: 'template',
type: 'select',
placement: 'right',
send: 'always',
value: 1,
source: [], //newJson (my new var)
/* should be in this format:
source: [{
value: 1,
text: 'text1'
}, {
value: 2,
text: 'text2'
}]*/
});
};
});
After the stringify, the output is close, but wont work. It looks like this:
{"value":2,"name":["Maintenance"]}
and needs to look like thisL
{value:2,name:'Maintenance'},
Here is a JSfiddle showing the output here.
it seems you are assigning complete array instead of value at index 0 try this
var item = {
"value": i,
"name": this[0] // gives elemnt at index 0
};
myarray.push(item);
FIDDLE
I was able to answer my own question. There might be a better way, but this works:
var myURL = 'https://api.myjson.com/bins/3nzdj';
$.getJSON(myURL, function(data) {
var output = '';
$.each(data.DATA, function(key, val) {
output +='{value: ';
output += "'"+key+"'";
output +=',text:';
output += "'"+val+"'";
output +='}';
output +=',';
});
var outputAdapted = '['+output+']'
$('.sectionsAvailable').editable({
name: 'template',
type: 'select',
placement: 'right',
send: 'always',
value: 1,
// should be in this format:
source:
function() {
return outputAdapted;
},
});
});
My FIDDLE I hope this can help someone else.
Below is my json data which is stored in Checklistdata.json, i want to display the key and the labels as check boxes using jquery,my jquery will only display the label with check box.Any help, i will be grateful.
[
{
"Beginning": [
{
"label": "Enter basic information"
},
{
"label": "Enter name of Vendor "
}
]
}
]
Below is my jquery!!
$.getJSON('Checklistdata.json', function (data) {
$.each(data, function (i, entity) {
$('#Checklist').append($('<input />', { 'type': 'checkbox','label': entity.label, 'value': entity.is_correct })).append(entity.answer + '<br />');
});
$("#checkboxes").on('change', '[type=checkbox]', function () {
console.log($(this).val());
});
});
The way you are iterating around the data is the problem. After you change data to:
var data= [
{
"Beginning": [
{ "label": "Enter basic information","id":1 },
{ "label": "Enter name of Vendor ","id":2 }
]
}
];
Change your line of code:
$.each(data, function(key, val) {
to
$.each(data[0].Beginning, function(key, val) {
That is because data is an array of object. After you make this change you will see it moving a step closer to what you want to achieve! That should give you idea to modify your code further to do what you want it to do.
Here is a FIDDLE that will probably get you started.
The arrays would be the equivalent of your json data.
You'd need to style it and change the format to suit your needs.
It's not very elegant, but seems to work.
JS
var myarray1 = ['y', 'n', 'y', 'y', 'y'];
var myarray2 = ['A', 'B', 'C', 'D', 'E'];
$('#mybutton').click(function(){
$.each(myarray2, function(key, value){
$('#holderdiv').append(value + "<input type='checkbox' />" + '<br />');
});
$('input[type=checkbox]').each(function(index){
if(myarray1[index] == 'y')
{
$(this).prop('checked', true);
}
});
});
EDIT:
Ok, here's the new FIDDLE that works with your array.
It's a good idea to use jsonlint.com to check the validity of your json array.
New JS
var mydata = {
"Beginning": [
{ "label": "Enter basic information", "id": 1 },
{ "label": "Enter name of Vendor ", "id": 2 }
]
};
var firstvar = mydata.Beginning[0].id;
$('#mybutton').click(function(){
$.each(mydata.Beginning, function(key, value){
$('#holderdiv').append(mydata.Beginning[key].label + "<input type='checkbox' />" + '<br />');
});
$('input[type=checkbox]').each(function(index){
if( mydata.Beginning[index].id == 1)
{
$(this).prop('checked', true);
}
});
});
I have got my answer. have to made some changes to JSON data storing, but it satisfies my requirement. So below is the answer with fiddle. http://jsfiddle.net/Suma_MD/fWLgD/2/
var data = getData(),
$checklist = $('#checklist');
data.forEach(function (v) {
var Description = v.Description;
$checklist.append('<br>' + Description);
var Array1=v.Checklist;
var Array2;
Array1.forEach(function(d){
Array2 = d.label;
$checklist.append('<br>' +"<input type='checkbox' />" + Array2 );
});
});
function getData() {
return [
{
"Description": "Beginning1",
"Checklist": [
{
"label": "Enter basic information",
},
{
"label": "Enter basic information",
},
{
"label": "Enter basic information",
},
{
"label": "Enter basic information",
}
]
},
{
"Description": "Beginning2",
"Checklist": [
{
"label": "Enter basic ",
},
{
"label": "Enter basic ",
},
{
"label": "Enter basic ",
},
{
"label": "Enter basic ",
}
]
}
];
}
HTML : <div id="checklist"></div>