I am using the following code to receive a json as response and represent them in a table.
$(document).ready(function() {
var settings = {
"async" : true,
"crossDomain" : true,
"url" : "Parse",
"method" : "GET",
"headers" : {
"content-type" : "application/json"
},
"processData" : false
}
$.ajax(settings).done(function(jsnData) {
var obj = JSON.parse(jsnData);
for (var i = 0, len = obj.length; i < len; i++) {
var j=0;
var trd="";
trd +="<tr>";
trd+="<td>"
+ obj[i].word
trd+= " </td>";
trd+="<td>"
+ "<select class='input-small'><option value=''>"+obj[i].senses+"</option></select>";//obj[i].senses
trd+= " </td>";
trd+="</tr>";
$('#userdata tr:last').after(trd);
}
});
});
</script>
The userdata is the id o the table I am using to feed this json response.
The Json format is
[
{
"word": "play",
"senses": ["n1","n2","n3"]
},
{
"word": "play1",
"senses": ["m1","m2","m3"]
},
{
"word": "play2",
"senses": ["j1","k2","l3"]
},
{
"word": "play3",
"senses": ["x","ny","z"]
},
{
"word": "play4",
"senses": ["p","q","r"]
}
]
In my table there are two columns,One for word and one for senses,but I want the senses column as drop down.I am getting the output as follow,
As you can see,the Option column which I want to use to represent senses,showing the senses for the respected word in one line,e.g. for word play its senses are showed as n1,n2,n3.I want them to be shown as drop down,i.e. for for word play,drop down values will be n1 n2 and n3 for word play1,drop down values will be m1 m2 and m3.
HTML code
<table id="userdata" border="2">
<tr>
<td><b>Word</b></td>
<td><b>Options</b></td>
</tr>
<tbody>
</tbody>
</table>
I tried hard but was not been able to do it in desired way.any help would be much appreciated.
use this
+ "<select class='input-small'>";
for(var k=0; i <obj[i].senses.length;k++){
trd+="<option value='"+obj[i].senses[k]+"'>"+obj[i].senses[k]+"</option>";
}
trd+="</select>";
Related
I have a sample JSON like this:
}
"vehicles":"4door",
"cars": {
"Toyota":"Camry",
"Ford":"Explorer",
"Nissan":"Altima",
"Jeep":"Wrangler"
},
"color":"red"
}
I'm trying to make an HTML table with 2 columns called something like "Make" and "Model" using the sample JSON with JQuery using the "cars" array out of the JSON without taking the other items vehicles and color. The "Make" would be the keys of the JSON and the "Model" would be the values of the keys. I'm trying to get it to look something like this below but in a table format. Any help or advice would be greatly appreciated.
Make Model
Toyota Camry
Ford Explorer
Nissan Altima
Jeep Wrangler
Use Object.keys which will give an array of keysThen you can iterate it and get the key value from the object and use template literals to create a row and finally append to the table
let cars = {
"Toyota": "Camry",
"Ford": "Explorer",
"Nissan": "Altima",
"Jeep": "Wrangler"
}
let getKeys = Object.keys(cars);
let row = '';
for (let i = 0; i < getKeys.length; i++) {
row += `<tr><td>${getKeys[i]}</td><td>${cars[getKeys[i]]}</td></tr>`
}
$('#carTable').append(row)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='carTable'>
</table>
Use Object.keys to get an array of the cars and loop through them using forEach loop. Using append in jquery append the row to the table
var data = {
"vehicles": "4door",
"cars": {
"Toyota": "Camry",
"Ford": "Explorer",
"Nissan": "Altima",
"Jeep": "Wrangler"
},
"color": "red"
}
var str='';
Object.keys(data.cars).forEach(e => {
str+='<tr><td>' + e + '</td><td>' + data.cars[e] + '</td></tr>';
})
$('#data').append(str)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">
<tr>
<td>Make</td>
<td>Model</td>
</tr>
</table>
You can also create your entire html from the script
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var html = ""
var json = {
"vehicles":"4door",
"cars": {
"Toyota":"Camry",
"Ford":"Explorer",
"Nissan":"Altima",
"Jeep":"Wrangler"
},
"color":"red"
}
html = "<table><thead><th><td>Make</td><td>Model</td></th></thead><tbody>"
for(var x in json.cars){
html+= "<tr><td>"+ x +"</td><td>"+ json.cars[x] +"</td></tr>"
}
html+="</tbody></table>"
$("#main").append(html)
});
</script>
</head>
<body>
<div id="main"></div>
</body>
</html>
Here I seen json format was not correct also get jsonObject.KeyName hold in variable then loop json that holds variable.
var obj = {"Toyota":"Camry", "Ford":"Explorer", "Nissan":"Altima", Jeep":"Wrangler"};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
}
}
After that you implement in html format.
var data = {
"vehicles": "4door",
"cars": {
"Toyota": "Camry",
"Ford": "Explorer",
"Nissan": "Altima",
"Jeep": "Wrangler"
},
"color": "red"
};
var cars = data.cars; // for better performance if large table
var tableData = Object.keys(cars).map(item => '<tr><td>' + item + '</td><td>' + cars[item] + '</td></tr>').join('');
$('#main>table').append(tableData)
<div id="main">
<table>
<tr>
<td>Make</td>
<td>Model</td>
</tr>
</table>
</div>
So, I was just about getting comfortable getting JSON data and displaying it in HTML when I ran in to the need to loop through items and display each keys and values. My objective is to display all 50 items in the JSON array and their information in a table. But whatever I try to do, the only output is nr 50. The last item in the array.
Here is my JSON:
{
"_embedded": {
"enheter": [
{
"organisasjonsnummer": "995742594",
"navn": "0-TAXI , KHAN TAIMUR",
"organisasjonsform": {
"kode": "ENK",
"beskrivelse": "Enkeltpersonforetak",
"_links": {
"self": {
"href": "https://data.brreg.no/enhetsregisteret/api/organisasjonsformer/ENK"
}
}
},
"registreringsdatoEnhetsregisteret": "2010-07-15",
"registrertIMvaregisteret": true,
"naeringskode1": {
"beskrivelse": "Drosjebiltransport",
"kode": "49.320"
},
"antallAnsatte": 0,
"forretningsadresse": {
"land": "Norge",
"landkode": "NO",
"postnummer": "1473",
"poststed": "LØRENSKOG",
"adresse": [
"Kulturhusgata 1"
],
"kommune": "LØRENSKOG",
"kommunenummer": "0230"
},
"institusjonellSektorkode": {
"kode": "8200",
"beskrivelse": "Personlig næringsdrivende"
},
"registrertIForetaksregisteret": false,
"registrertIStiftelsesregisteret": false,
"registrertIFrivillighetsregisteret": false,
"konkurs": false,
"underAvvikling": false,
"underTvangsavviklingEllerTvangsopplosning": false,
"maalform": "Bokmål",
"_links": {
"self": {
"href": "https://data.brreg.no/enhetsregisteret/api/enheter/995742594"
}
}
},//This is just the one item, the list goes on all the way up to 50.'
This is the code for extracting the data:
jQuery.ajax({
url: 'https://data.brreg.no/enhetsregisteret/api/enheter?page=0&size=50&naeringskode=49.3,49.4,49.5&sort=navn.norwegian,asc',
type: 'GET',
data: {},
dataType: 'json',
success: (response) => {
var listenhet = (response);
var enhetArray = listenhet._embedded.enheter;
for (var i = 0; i < enhetArray.length; i++) {
console.log(enhetArray[i].navn);
//Creating table
var table ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";
//Showing the table inside tbody
document.getElementById("myTB").innerHTML = table;
}
console.log(response);
},
error: (response) => {
console.log(response);
}
})
Here is the table
<table class="table">
<thead>
<tr>
<th scope="col">Sted</th>
<th scope="col">Firmanavn</th>
<th scope="col">MVA Registrert</th>
<th scope="col">Reg Dato</th>
<th scope="col">Beskrivelse</th>
</tr>
</thead>
<tbody id="myTB">
</tbody>
</table>
This is my output:
This is my console:
So, as you see, the console logs all 50 items. While my table only displays the last item in the array. How can I display all 50 items to the table so it becomes 50 table rows with the information I need about each item?
You are creating a new variable 'var table' on each iteration
which leads to erase the last contained data from the table variable and initialize with latest data. So that the data from the last iteration only exists in the table variable.
Try creating a global variable outside of the loop
var table = "";
for (var i = 0; i < enhetArray.length; i++) {
console.log(enhetArray[i].navn);
//Creating table
var rowData ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";
// Store the value in 'table'
table+= rowData;
}
And assign the 'table' variable to the 'myTB' from out side of the loop.
document.getElementById("myTB").innerHTML = table;
just replace
document.getElementById("myTB").innerHTML = table;
with
document.getElementById("myTB").innerHTML += table;
You are creating this variable:
var table ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";
And adding it to the innerHTML of #myTB
document.getElementById("myTB").innerHTML = table;
But that means table has a new value in each iteration of the loop. So in the last iteration, whatever value is assigned to it, that is displayed in the table.
You need to store the value in a variable outside the loop like:
var total = ""; // Let this contain all the text
for (var i = 0; i < enhetArray.length; i++) {
console.log(enhetArray[i].navn);
//Creating table
var table ="<tr><td>"+enhetArray[i].forretningsadresse.kommune+"</td><td>"+enhetArray[i].navn+"</td><td>"+enhetArray[i].registrertIMvaregisteret+"</td><td>"+enhetArray[i].registreringsdatoEnhetsregisteret+"</td><td>"+enhetArray[i].naeringskode1.beskrivelse+"</td></tr>";
// Store the value in 'total'
total+= table;
}
// Set innerHTML to the combined value
document.getElementById("myTB").innerHTML = total;
I am performing some ASP.NET gridview conversions using the datatables.net plug-in. The answer to why I am doing this is more involved and can be debated. However, I need some help with one of the issues I am running into.
Using Javascript to convert the gridview on the page was actually quite simple and works well. The major issue is that I want to have a fixed 'total' row (footer) within the body of the datatable so that it remains responsive just like the rest of the table.
I have attempted to add a footer using the code-behind, and I can populate that footer with total data, but it is not responsive with the rest of the table. I am assuming because the <tfoot> is outside of the <tbody>.
Using javascript, I have successfully added a new datatable row and I can output the data to the console, but I am unable to populate the added row with the object data.
Javascript:
var sum;
$(document).ready(function () {
var table = $('#cphPage_gvTaxColl').DataTable();
//convert string to int
var intVal = function (i) {
var j = $("<span/>");
var txt = j.html(i).text();
// alert('txt :' + txt);
var myVal = typeof txt === 'string' ?
parseFloat(txt.replace(/[^\d.-]/g, '')) :
typeof txt === 'number' ?
i : 0;
return myVal || 0;
};
//format integer as currency
var formatSum = function (myVal) {
return accounting.formatMoney(myVal, {
symbol: "$",
precision: 2,
thousand: ",",
decimal: ".",
format: {
pos: "%s %v",
neg: "%s (%v)",
zero: "%s 0.00"
}
});
};
//add total row and determine index
table.row.add(['GRAND TOTAL']).draw();
var total_row = (table.row().count() + 1);
var total_col = (table.row(total_row).column().count + 1);
//alert
console.log('total row: ' + total_row);
//loop columns
table.columns('.sum').every(function () {
sum = this
.data()
.reduce(function (a, b) {
console.log('adding ' + intVal(a) + ' and ' + intVal(b));
return intVal(a) + intVal(b);
});
//alert
console.log('sum: ' + sum);
console.log('column row 2 val: ' + this.data().row([2]));
$(this.cell.node( total_row )).html(
formatSum(sum)
);
});
});
How do I present the object data within the datarow?
I am also receiving the following error message, and I am not certain which parameter is missing ( the 2nd and 3rd columns are null ):
Error message
I have included a screenshot with the console data, and if you need it I can provide the .aspx markup:
Page + cosole log output
I'm still learning the ins-and-outs of this stuff. Any guidance you can provide is greatly appreciated.
Thanks in advance!
Here is my solution:
The html-table for datatables should have <tfoot>
Something like this:
<table id='table'>
<tbody>
<tr><td></td></tr>
</tbody>
<tfoot>
<tr><td></td></tr>
</tfoot>
</table>
Define footerCallback field
Datatables initialization:
$('#table').dataTable({
...
"footerCallback": _footerDrawn
...
});
footerCallback:
I use server-side data, so my source of data for footer is just another field of of ajax-response:
_footerDrawn: function( row, data, start, end, display ) {
var table = $('#table').dataTables();
var json = table.api().ajax.json();
// assign values to each cell of the footer from json.total array
$.each( table.api().columns().indexes(), function( index ) {
$( table.api().column( index ).footer() ).html( json.total[index] );
});
}
}
json.total contains array of string to print in footer row
I am trying to make a website for a tabletop game a friend of mine created, and I want to store all the data in JSON files and pull up the data in HTML files with Javascript. I want to, for example, store each class in a separate file, with its skill list (only listing the skill name and level learned in this file) included in the file, and a master list of all skills, their costs, and their descriptions in another file. Basically, I want to treat two or more JSON files like linked tables in a database.
In this example, this is what would be found in the class's file:
{
"name": "Class 1",
"skills": [
{
"name": "Skill 1",
"level": 1
},
{
"name": "Skill 2",
"level": 2
},
{
"name": "Skill 3",
"level": 3
}
]
}
And this is the master skill file:
{
"skills": [
{
"name": "Skill 1",
"desc": "This is the first skill.",
"cost": "1 MP"
},
{
"name": "Skill 2",
"desc": "This is the second skill.",
"cost": "2 HP"
},
{
"name": "Skill 3",
"desc": "This is the third skill.",
"cost": "3 Gold"
},
{
"name": "Skill 4",
"desc": "This is a skill from a different class.",
"cost": "All MP"
}
]
}
And I want the HTML file to output something like this, using these two separate JSON files:
<h1>Class 1</h1>
<table>
<tr>
<td>Skill 1</td>
<td>Level 1</td>
<td>1 MP</td>
<td>This is the first skill.</td>
</tr>
<tr>
<td>Skill 2</td>
<td>Level 2</td>
<td>2 HP</td>
<td>This is the second skill.</td>
</tr>
<tr>
<td>Skill 3</td>
<td>Level 3</td>
<td>3 Gold</td>
<td>This is the third skill.</td>
</tr>
</table>
Can this be done? And if so, how?
jsBin demo
// GET MASTER FILE
$.getJSON( "db/master.json", function( data ) {
var masterSkills = data.skills; // Store master Object
// Now that we've read the master data let's see how many
// (cause you're working with Arrays)
// of those skills has the Class 1 file
// GET Class 1 FILE
$.getJSON( "db/class.json", function( data ) {
// Collect Class 1 skills (3 of them) adding data from
// our stored masterSkills
var rows = []; // Array to create rows
$.each( data.skills, function( i, val ) { // 3 of them
rows.push( "<tr>"+
"<td>"+ val.name +"</td>"+
"<td>Level "+ val.level +"</td>"+
"<td>"+ masterSkills[i].cost +"</td>"+
"<td>"+ masterSkills[i].desc +"</td>"+
"</tr>" );
});
// Append collected data do some element ("body")
$('<h1/>',{html: data.name }).appendTo("body");
$( "<table/>", { html: rows.join("") }).appendTo("body");
});
});
The above is usable ONLY if the sequence of both files matches the array count,
otherwise if you want to be sure to get only the right data that matches the exact level (in the case your class file has stored data in a non-incremental way) you'll have to change a bit the JSON structure, to prevent unnecessary loops to find an exact "Level" match. One way would be (master file):
{
"skill1" : {
"foo":"bar"
},
"skill2" : {
"blu":"bla"
},
}
now, instead of searching trough all "name" properties you can directly target the desired level and extract the values.
http://api.jquery.com/jquery.getjson/
Please correct me if I misunderstood your question, but you'll want to do something like this:
Store your master json file in on the server, e.g. data.json.
Either store everything else in the same file, like so: {"classes": [ classes go here ]}, or each in a separate file, like class1.json, class2.json, etc.
Then, use js to pull the data from the files to your html page, like so:
$.getJSON('data.json', function (data) { // do this for all your files
// process your data here
});
Then, within the callbacks, use basic DOM manipulation to create your table, e.g. (a simplified example):
var html = $("<p>The skill's name: " + data["skills"][0]["name"]);
$("#yourtable").append(html);
EDIT: if you want to do this for each skill, it's as simple as
var skills = data["skills"];
$.each(skills, function (index) {
// do your DOM stuff here (skills[index] is your skill)
});
That will iterate over each skill, and do the same thing for each one.
EDIT 2: here is the full code you asked for.
// assume class data is stored in files called [classname].json
var classname = "yourclass", masterfile = "master.json";
// fetch data from the master file
$.getJSON(masterfile, function (masterData) {
// fetch data from your class file
$.getJSON(classname + ".json", function (classData) {
var skills = classData["skills"]
// iterate over each skill in the class
for(var i = 0; i < skills.length; i++) {
var skill = skills[i];
// iterate over each skill in the master file
for(var j = 0; j < masterData["skills"].length; j++) {
// check if the names of the skill in the class and the skill in the master file match
if(masterData["skills"][j][name] === skill["name"]) {
// the skill names match
var s = masterData["skills"][j];
// s is now your skill variable, where s["cost"] is the cost, et cetera
// now, do your DOM manipulation using the skill data
}
}
}
});
});
I'm inserting rows in a <table> that are bound to a JSON object. A cell in the table contains a <select> that needs to contain the number of objects, so 7 objects would produce 7 <option>s, 1-7.
Can this be done in the template definition?
Edit: I've added sample data and markup. From this data, I would want to add 3 <option>s (1-3) to the DisplayOrder <select> and have the appropriate <option> selected for each <select>.
Example: http://jsfiddle.net/4SxTS/
var data = [{
"Id": 1,
"DisplayOrder": 1,
"LabelText": "Unit On-Line Status:"},
{
"Id": 2,
"DisplayOrder": 2,
"LabelText": "AGC Pct:"},
{
"Id": 3,
"DisplayOrder": 3,
"LabelText": "Main Steam Heat Rate
}];
<table border="1" cellpadding="0" cellspacing="0">
<thead><tr><th>Display Order</th><th>Label Text</th></tr></thead>
<tbody></tbody>
</table>
<script id="attributeTemplate" type="text/x-jquery-tmpl">
<tr>
<td><select name="DisplayOrder"></select></td>
<td><input type="text" name="LabelText" value="${LabelText}" /></td>
</tr>
</script>
I'm not sure exactly what you mean without some sample data and markup, but I think the main part of your question deals with looping through numbers and rendering an option tag for each number. You could do this by creating an array containing "N" elements and then using {{each}}, but I think that using a custom template tag works well here:
Define a {{for}} tag that iterates through numbers 0 to n:
$.extend(jQuery.tmpl.tag, {
'for': {
open: "for(var $i = 0; $i < $1; $i++) {",
close: "}"
}
});
Use the new tag in a template:
<script type="text/html" id="row-tmpl">
{{each Rows}}
<tr>
<td>${Title}</td>
<td>${Description}</td>
<td>
<select>
{{for $data.TotalObjects}}
<option>${$i}</option>
{{/for}}
</select>
</td>
</tr>
{{/each}}
</script>
Called with:
var rows = {
TotalObjects: 5,
Rows: [{
Title: 'Test Row',
Description: 'Test Row Description'
},
{
Title: 'Another Row',
Description: 'Another Row Description'
}]
};
Best demonstrated in a working example: http://jsfiddle.net/xgE3Y/
Your situation might be even simpler, but my answer should enable you to at least use a simple for loop in a template and act on each iteration's value.
Maybe something like this:
$(function () {
var thisSelectObjects = 8;
var thatSelectObjects = 2;
$.fn.setOptions = function (options) {
var settings = {
'selectNum': 1
};
return this.each(function () {
if (options) {
$.extend(settings, options);
}
for (i = 0; i < settings.selectNum; i++) {
$(this).append('<option>' + i + '<option/>');
}
});
};
$('#thisSelect').setOptions({ 'selectNum': thisSelectObjects });
$('#thatSelect').setOptions({ 'selectNum': thatSelectObjects });
});
Html:
<body>
<select id='thisSelect'></select>
<select id='thatSelect'></select>
</body>