There is a JavaScript object and I need to retrieve free_time, done_ratio, criticalTask, dependency for each task element.
This is what i have done, but it doesn't work.
var mock_data_allocation = {"allocation":[{"id":7,"name":"Manoj D","limit":4.0,"available_time":16.0,"tasks":[{"id":34,"name":"issue_25","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":3,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[]},{"id":36,"name":"issue_27","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":3,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[33,34]},{"id":38,"name":"issue_29","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":5,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[35,36]},{"id":39,"name":"issue_30","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":4,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":true,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Manoj D","dependency":[37,38]}]},{"id":5,"name":"Thisun H","limit":4.0,"available_time":16.0,"tasks":[{"id":33,"name":"issue_24","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":5,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":false,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Thisun H","dependency":[]},{"id":35,"name":"issue_26","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":2,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":false,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Thisun H","dependency":[]},{"id":37,"name":"issue_28","projectId":3,"startDate":"2015-12-28","dueDate":"2015-12-31","done_ratio":0,"estimate":6,"remaining":0,"sprintId":"2015-12-28_2015-12-31","criticalTask":false,"assigned":true,"tracker":"Bug","status":"New","assignedTo":"Thisun H","dependency":[34]}]}]};
$(mock_data_allocation.allocation).each( function(i, value){
$('.taskdetail').append('<tr>' +
'<td>'+ (i+1) +'</td>'+
'<td>'+ value.tasks.name +'</td>'+
'<td>'+value.tasks.free_time+'</td>'+
'<td>'+value.tasks.done_ratio+'</td>'+
'<td>'+value.tasks.criticalTask+'</td>'+
'<td>'+value.tasks.dependency.length+'</td>'+
'</tr>');
});
<tbody class="taskdetail"></tbody>
Currently the output is:
1 undefined undefined 0 true 0
2 undefined undefined 0 false 0
The tasks property of the value objects is an array of objects but your code assumes that it's an object. Your code fails as the tasks array doesn't have dependency property and subsequently value.tasks.dependency.length fails as value.tasks.dependency returns undefined and undefined doesn't have length property.
You should either get a specific element from the tasks array:
.append('<tr>' +
'<td>'+ (i+1) +'</td>'+
'<td>'+ value.tasks[0].name +'</td>'+
'<td>'+value.tasks[0].free_time+'</td>'+
'<td>'+value.tasks[0].done_ratio+'</td>'+
'<td>'+value.tasks[0].criticalTask+'</td>'+
'<td>'+value.tasks[0].dependency.length+'</td>'+
'</tr>');
or iterate through it:
var $target = $('.taskdetail');
$.each(mock_data_allocation.allocation, function(i, value) {
$.each(value.tasks, function(ii, task) {
$target.append('<tr>' +
'<td>'+ (ii+1) +'</td>'+
'<td>'+ task.name +'</td>'+
'<td>'+task.free_time+'</td>'+
'<td>'+task.done_ratio+'</td>'+
'<td>'+task.criticalTask+'</td>'+
'<td>'+task.dependency.length+'</td>'+
'</tr>');
});
});
Also you should not create a jQuery object by passing a regular object to jQuery. Use the $.each utility function instead.
You should try this....
$.each(mock_data_allocation.allocation,function(i, value){
$.each(value.tasks,function(j,val){
$('.taskdetail').append('<tr>' +
'<td>'+ (j+1) +'</td>'+
'<td>'+ val.name +'</td>'+
'<td>'+val.free_time+'</td>'+
'<td>'+val.done_ratio+'</td>'+
'<td>'+val.criticalTask+'</td>'+
'<td>'+val.dependency.length+'</td>'+
'</tr>');
});
});
$(mock_data_allocation.allocation) is nothing, in fact $(mock_data_allocation) is nothing.
You may want jQuery.each( mock_data_allocation.allocation, function ... ?
Many answers here point a main issue, which is the way the object is explored,and I agree.
But I don't understand why there is no answer pointing another issue: the needed result comes from two different levels in the original object.
At the task level are the informations name, done_ratio, and criticalTask.
But it's one level up that resides free_time (in fact named available_time), which is the same for all tasks (note #2 in the code below).
The same applies for the 1st <td>, which includes a counter: this one might be computed either globally or at the tasks level (note #1 in the code below).
Here is a really working solution (see this fiddle):
var all = mock_data_allocation.allocation;
for (var i = 0, n = all.length; i < n; i++) {
var availTime = all[i].available_time,
tasks = all[i].tasks;
for (var j = 0, m = tasks.length; j < m; j++) {
var task = tasks[j];
$('.taskdetail').append(
'<tr>' +
'<td>' + (i + 1) + '-' + (j + 1) +'</td>'+ // <-- #1
'<td>' + task.name + '</td>' +
'<td>' + availTime + '</td>' + // <-- #2
'<td>' + task.done_ratio + '</td>' +
'<td>' + task.criticalTask + '</td>' +
'<td>' + task.dependency.length + '</td>'+
'</tr>'
);
}
}
It seems to me that you must unpack the tasks array
var mock_data_allocation = {
"allocation": [{
"id": 7,
"name": "Manoj D",
"limit": 4.0,
"available_time": 16.0,
"tasks": [{
"id": 34,
"name": "issue_25",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 3,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": []
}, {
"id": 36,
"name": "issue_27",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 3,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": [33, 34]
}, {
"id": 38,
"name": "issue_29",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 5,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": [35, 36]
}, {
"id": 39,
"name": "issue_30",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 4,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": true,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Manoj D",
"dependency": [37, 38]
}]
}, {
"id": 5,
"name": "Thisun H",
"limit": 4.0,
"available_time": 16.0,
"tasks": [{
"id": 33,
"name": "issue_24",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 5,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": false,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Thisun H",
"dependency": []
}, {
"id": 35,
"name": "issue_26",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 2,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": false,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Thisun H",
"dependency": []
}, {
"id": 37,
"name": "issue_28",
"projectId": 3,
"startDate": "2015-12-28",
"dueDate": "2015-12-31",
"done_ratio": 0,
"estimate": 6,
"remaining": 0,
"sprintId": "2015-12-28_2015-12-31",
"criticalTask": false,
"assigned": true,
"tracker": "Bug",
"status": "New",
"assignedTo": "Thisun H",
"dependency": [34]
}]
}]
};
$(mock_data_allocation.allocation).each(function(i, value) {
$(value.tasks).each(function(index, el) {
$('.taskdetail').append('<tr>' +
'<td>' + (i + 1) + '</td>' +
'<td>' + el.name + '</td>' +
'<td>' + el.free_time + '</td>' +
'<td>' + el.done_ratio + '</td>' +
'<td>' + el.criticalTask + '</td>' +
'<td>' + el.dependency.length + '</td>' +
'</tr>');
});
});
https://jsfiddle.net/
Your problem lies in the use of $(mock_data_allocation.allocation).each There are two different .each functions in JQuery
$(selector).each() - Used to Iterate over a jQuery object
and
jQuery.each() - A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
mock_data_allocation is not a DOM element and so trying to make it into a JQuery object with $(mock_data_allocation.allocation) fails because mock_data_allocation.allocation is not a DOM element.
You need to iterate over a data object so instead of
$(mock_data_allocation.allocation).each( function(i, value){...
you should be doing
$.each(mock_data_allocation.allocation, function(i, value){...
That will cure the 'undefined' problem.
Related
Here is my Json array. I want to retrieve child arrays and I need to display all the invoices details under the project section. Please check the attached screenshot. In the screenshot you can see only last invoice details only displaying to all other projects. The last invoice number 1005 is showing for all. How can I show invoice details based on the project details?
When child row is empty,project details (parent) also not showing.Am getting projectinvoicesection: [] Array 0. I need to display project details and no record found in invoice section. But now am getting array zero.
[{
"parent": {
"project_ID": "1",
"project_title": "Network and Telephone Points",
"particulars": "Test Description",
"project_amount": "10000.00",
"type": "One Time",
},
"child": [{
"invoice_No": "1002",
"received_Amt": "0.00",
"invoice_amount": "472.50",
"proje_ID": "1",
"invoice_Date": "2021-08-31"
}]
},
{
"parent": {
"project_ID": "2",
"project_title": "Configuration and Programming",
"particulars": "test description",
"project_amount": "2000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1004",
"received_Amt": "0.00",
"invoice_amount": "245.70",
"proje_ID": "2",
"invoice_Date": "2021-08-30"
}]
},
{
"parent": {
"project_ID": "3",
"project_title": "Coffee ERP",
"particulars": "test",
"project_amount": "50000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1000",
"received_Amt": "0.00",
"invoice_amount": "1820.70",
"proje_ID": "3",
"invoice_Date": "2021-08-19"
},
{
"invoice_No": "1001",
"received_Amt": "0.00",
"invoice_amount": "1773.45",
"proje_ID": "3",
"invoice_Date": "2021-08-24"
}
]
},
{
"parent": {
"project_ID": "6",
"project_title": "sample project new design",
"particulars": "Test Project new",
"project_amount": "4000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1005",
"received_Amt": "0.00",
"invoice_amount": "283.50",
"proje_ID": "6",
"invoice_Date": "2021-08-21"
}]
}
]
I have tried this code below:
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i + 1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
//alert(t1)
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #337ab7;color: white;' class='accordion-toggle'><td>" + sl + "</td><td>" + t4 + "</td><td>" + t1 + "</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='border-collapse:collapse;'><thead><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
}
for (var property in object) {
//alert(object[property].invoice_No);
var t6 = format(object[property].invoice_Date);
var t7 = object[property].invoice_No;
var t8 = object[property].invoice_amount;
var t9 = object[property].received_Amt;
var t10 = object[property].proje_ID; //invoice table's project id
var trtoggle = "<tr><td>" + t6 + "</td><td>" + t7 + "</td><td>" + t8 + "</td><td class=''>" + t9 + "</td><td class=''><input type='checkbox' name='myTextEditBox' value='checked' /> checkbox</td></tr>";
$(".tableinvoice_proj").append(trtoggle);
}
Here is the screenshot
PHP MODAL:
public function list_all_projects_invoice($data) //project section display with ALL Category
{
$array_store = array();
foreach($this->one_allcategory($data) as $row) {
$child = $this->many_allcategory($row['project_ID']);
if($child) {
$return = array_merge(array("parent" => $row), array("child" =>$child));
array_push($array_store, $return);
}
}
return $array_store;
}
public function one_allcategory($data) {
$query = $this->db->select("*")
->where("comp_ID", $data)
->get("project_details")
->result_array();
return $query;
}
public function many_allcategory($id) {
$query = $this->db->select('invoice_No,received_Amt,invoice_amount,proje_ID,invoice_Date')
->where("proje_ID", $id)
->get("invoice_details")
->result_array();
return $query;
}
It's because you append trtoggle to .tableinvoice_proj without specifying the exact element with this class then trtoggle append to all of element with .tableinvoice_proj class.
According to the code you can try
$(".tableinvoice_proj").last().append(trtoggle);
instead of
$(".tableinvoice_proj").append(trtoggle);
new_data = new Object();
new_data.projectinvoicesection = [{
"parent": {
"project_ID": "1",
"project_title": "Network and Telephone Points",
"particulars": "Test Description",
"project_amount": "10000.00",
"type": "One Time",
},
"child": [{
"invoice_No": "1002",
"received_Amt": "0.00",
"invoice_amount": "472.50",
"proje_ID": "1",
"invoice_Date": "2021-08-31"
}]
},
{
"parent": {
"project_ID": "2",
"project_title": "Configuration and Programming",
"particulars": "test description",
"project_amount": "2000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1004",
"received_Amt": "0.00",
"invoice_amount": "245.70",
"proje_ID": "2",
"invoice_Date": "2021-08-30"
}]
},
{
"parent": {
"project_ID": "3",
"project_title": "Coffee ERP",
"particulars": "test",
"project_amount": "50000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1000",
"received_Amt": "0.00",
"invoice_amount": "1820.70",
"proje_ID": "3",
"invoice_Date": "2021-08-19"
},
{
"invoice_No": "1001",
"received_Amt": "0.00",
"invoice_amount": "1773.45",
"proje_ID": "3",
"invoice_Date": "2021-08-24"
}
]
},
{
"parent": {
"project_ID": "6",
"project_title": "sample project new design",
"particulars": "Test Project new",
"project_amount": "4000.00",
"type": "One Time",
"period_type": " ",
},
"child": [{
"invoice_No": "1005",
"received_Amt": "0.00",
"invoice_amount": "283.50",
"proje_ID": "6",
"invoice_Date": "2021-08-21"
}]
},
{
"parent": {
"project_ID": "9",
"project_title": "TEST",
"particulars": "NO RESULT",
"project_amount": "0",
"type": "One Time",
"period_type": " ",
},
"child": []
}
]
for (var i = 0; i < new_data.projectinvoicesection.length; i++) {
var sl = i + 1;
//alert(t6)
var t1 = new_data.projectinvoicesection[i]['parent'].project_amount;
//alert(t1)
var t2 = new_data.projectinvoicesection[i]['parent'].particulars;
var t3 = new_data.projectinvoicesection[i]['parent'].project_ID;
var t4 = new_data.projectinvoicesection[i]['parent'].project_title;
var t5 = new_data.projectinvoicesection[i]['parent'].type;
var t56 = new_data.projectinvoicesection[i]['parent'].period_type;
var object = new_data.projectinvoicesection[i]['child'];
var tr = "<tr data-toggle='collapse' data-target='#demo" + t3 + "' style='background-color: #337ab7;color: white;' class='accordion-toggle'><td>" + sl + "</td><td>" + t4 + "</td><td>" + t1 + "</td><td style='white-space: nowrap;'>" + t5 + " " + t56 + "</td><td><button class='open-button-project-edit btn' data-toggle='modal' data-backdrop='static' data-keyboard='false' data-target='#exampleModal_2' onclick='openForm3(" + t3 + ")' style='color: #fff;background-color: #398439;border-color: #255625;'>EDIT</button></td></tr><tr><td colspan='6' class='hiddenRow'><div class='accordian-bodyproj collapse' id='demo" + t3 + "'> <table id='tableinvoice_proj' class='tableinvoice_proj' style='border-collapse:collapse;'><thead><tr><th>Invoice Date</th><th>Invoice Number</th><th>Invoice Amount</th><th>Received Amount</th><th>Generate Receipt</th></tr></thead><tbody></tbody></table>";
$("#tableproject").append(tr);
$("#tableproject").append('</div></td></tr>');
if( !object || object.length < 1)
{
var trtoggle = `<tr ><td style='text-align:center;' colspan='5' > No records found!</td></tr>`;
} else
{
var trtoggle = '';
for ( var property in object ) {
//alert(object[property].invoice_No);
var t6 = object[property].invoice_Date;
var t7 = object[property].invoice_No;
var t8 = object[property].invoice_amount;
var t9 = object[property].received_Amt;
var t10 = object[property].proje_ID; //invoice table's project id
trtoggle += "<tr><td>" + t6 + "</td><td>" + t7 + "</td><td>" + t8 + "</td><td class=''>" + t9 + "</td><td class=''><input type='checkbox' name='myTextEditBox' value='checked' /> checkbox</td></tr>";
}
}
$(".tableinvoice_proj").last().append(trtoggle);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tableproject">
</table>
Your second for loop needs to be inside of the first for loop (nested):
//You have
For(){
}
For(){
}
//You need
For(){
For(){
}
}
I have a time calculation tool which you can find in the following fiddle link. Once someone has selected a platform, task type, component and number of units, the number of units entered should be multiplied with selected component value and show it on the below table. I have managed to get the all populated values but can't do the math. I have tried several attempts but it wasn't working.
var myJson = {
"platforms": [
{
"name": "Sitecore",
"id": "sitecore",
"tasktype": [
{
"name": "Promobox",
"id": "promobox",
"components": [
{
"name": "Accordion",
"id": "accordion",
"time": "20"
},
{
"name": "Box 1",
"id": "box1",
"time": "30"
}
]
},
{
"name": "Video",
"id": "video",
"components": [
{
"name": "Box 2",
"id": "box2",
"time": "25"
},
{
"name": "Box 3",
"id": "box3",
"time": "30"
}
]
}
]
},
{
"name": "Siab",
"id": "siab",
"tasktype": [
{
"name": "Newswire",
"id": "newswire",
"components": [
{
"name": "Box 4",
"id": "box5",
"time": "50"
},
{
"name": "Box 5",
"id": "box5",
"time": "40"
}
]
},
{
"name": "Task Type New",
"id": "tasktypenew",
"components": [
{
"name": "Box 6",
"id": "box6",
"time": "20"
},
{
"name": "Box 7",
"id": "box7",
"time": "100"
}
]
}
]
}
]
};
$.each(myJson.platforms, function (index, value) {
var platform_id;
var tasktype_id;
var component_id;
$("#platform").append('<option rel="' + index + '" value="' + value.id + '">' + value.name + '</option>');
$("#platform").change(function () {
$("#tasktype, #component").find("option:gt(0)").remove();
$("#tasktype").find("option:first").text("Loading...");
platform_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype, function (index1, value1) {
$("#tasktype").find("option:first").text("Select Task Type");
$("#tasktype").append('<option rel="' + index1 + '" value="' + value1.id + '">' + value1.name + '</option>');
});
});
$("#tasktype").change(function () {
$("#component").find("option:gt(0)").remove();
$("#component").find("option:first").text("Loading...");
tasktype_id = $(this).find('option:selected').attr('rel');
$.each(myJson.platforms[platform_id].tasktype[tasktype_id].components, function (index2, value2) {
$("#component").find("option:first").text("Select Component");
$("#component").append('<option rel="' + index2 + '" value="' + value2.time + '">' + value2.name + '</option>');
});
});
});
$(document).ready(function () {
$('#calculate').click(function () {
$('#calc input, #calc select').each(
function (index) {
var input = $(this);
$('#data tbody').append('<tr><td>' + input.val() + '</td></tr>');
});
});
});
JS Fiddle
Ok this took a lot of debugging. You were building your table wrong and not storing data properly. The whole fishing for data was problematic. Here is the debugged calculator:
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
console.log(tr);
$('#calc input, #calc select').each( function (index) {
console.log($(this));
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + input.val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
});
});
notice:
Change of table structure format.
Now appending td's to single tr each time in order to sustain table-row consistency.
Fishing data from row with the help of adding class tag identifier to each td
Showing result.
update fiddle link:
https://jsfiddle.net/x4rLuf88/1/
AJAX:
{
"data": [
{
"id": 1,
"name": "Dashboard",
"url": "/",
"icon": "icon-home",
"child_of": null,
"show": 1,
"admin": 0
},
{
"id": 2,
"name": "Submenu 3",
"url": "http://stackoverflow.com",
"icon": null,
"child_of": null,
"show": 1,
"admin": 0
},
]
}
JS:
$('#table-editable').dataTable({
"ajax": {
"url": "/api/menu",
"type": "GET",
},
"columns": [
{ "data": "id" },
{ "data": "name" },
{ "data": "url" },
{ "data": "icon" },
{ "data": "child_of" },
{ "data": "show" },
{ "data": "admin" }
]
});
So I'm using AJAX to fill up data in tables. It is working.
I am using this: DataTables: Inline Editing for creating new row. (Check Adding row & Edit Mode in link)
Problem:
Consider I've 13 rows. So IDs will be 1, 2, 3... 13.
While creating new row:
It does this: oTable.fnAddData('', '',....);
So when I add new row, it gives me error:
DataTables warning: table id=table-editable - Requested unknown parameter 'id' for row 14. For more information about this error, please see datatables.net/tn/4
So, basically it tries to fetch row id 14. But, there's no row with id 14.
So what is the solution?
var data = [
{
"CategoryID": 1,
"CategoryName": "Soler Power Plant",
"CategoryProducts": [
{
"ID": 1,
"Name": 'Commercial Solar Power Plant',
"SubTitle": 'Eco, Eco Friendly, Energy, Green, Solar',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'Having a pre-determined quality administration system, we are thoroughly involved in delivering Commercial Solar Power Plant.',
"ImageUrl": 'assets/images/Products/Sola-power-plant.jpg',
},
{
"ID": 2,
"Name": 'Industrial Solar Power Plants',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": 'So as to become a preferential business name, we are thoroughly engrossed in shipping an inclusive collection of Industrial Solar Power Plants.',
"ImageUrl": 'assets/images/Products/Industrial_Solar_Power_Plants.jpg',
},
{
"ID": 3,
"Name": 'On Grid Solar Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 1.1 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Plant.jpg',
},
{
"ID": 4,
"Name": 'On Grid Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of On Grid Solar Power Plant. To sustain the quality, our products are made under the guidance of industry top professionals.",
"ImageUrl": 'assets/images/Products/On_Grid_Solar_Power_Plant.jpg',
},
{
"ID": 5,
"Name": 'Solar Power Plant',
"SubTitle": 'Eco Friendly, Save Energy',
"Brand": 'ACS',
"Usage": '',
"Type": '',
"Price": 'Rs 5 Lakh / Unit',
"Body_Material": '',
"Description": "We are the leading firm of Solar Power Plant. To sustain the quality, our products are made under the guidance of industry certified professionals.",
"ImageUrl": 'assets/images/Products/Solar_Power_Plant.jpg',
},
]
}
]
function GetProducts() {
var products = data;
$.each(products, function () {
//var product = products.filter(filterByID)
var product = this;
$('#ProductDetails').append('<h2 class="text-center">' + this.CategoryName + '</h2>');
var details = product;
$.each(details.CategoryProducts, function () {
tempData = tempData + '<div class="col-md-4 col-sm-6">' +
'<div class="project-box">' +
'<div class="frame-outer">' +
'<div class="frame">' +
'<img style="width:350px;" src="' + this.ImageUrl + '" class="attachment-340x220 size-340x220 wp-post-image" alt="">' +
'</div>' +
'</div>' +
'<div class="text-box">' +
'<h3><a>' + this.Name + '</a></h3>' +
'<div class="tags-row">' +
'<a class="link">' + this.SubTitle + '</a>' +
'</div>' +
'<p>' + this.Description + '</p>' +
//'More Details' +
'</div>' +
'</div>' +
'</div>';
});
$('#ProductDetails').append('<div class="row">' + tempData + '</div>');
tempData = '';
});
}
Here, it's my own code may be it's help you
I want to dynamically create a table from JSON object and I will have to consider the rowspans.
So my array is something like below and the table will then display Id, Name, Age in a td and hobbies, skills, language will be row spanned.
My table with the below array will then look like
var myArr = [{
"Id": 1,
"Name": 'Ken',
"Age": '30',
"Hobbies": [{
'HobbyId': 1,
'HobbyName': 'Swimming'
}, {
'HobbyId': 2,
'HobbyName': 'Reading'
}],
"Skills": [{
'SkillId': 1,
'SkillName': 'PHP'
}, {
'SkillId': 2,
'SkillName': 'MySQL'
}],
"Language": [{
'LangId': 2,
'LangName': 'English'
}, {
'LangId': 3,
'LangName': 'Chinese'
}]
},
{
"Id": 2,
"Name": 'Mike',
"Age": '20',
"Hobbies": [],
"Skills": [],
"Language": []
},
{
"Id": 3,
"Name": 'Charlie',
"Age": '25',
"Hobbies": [{
'HobbyId': 5,
'HobbyName': 'Dance'
}, {
'HobbyId': 6,
'HobbyName': 'Sing'
}, {
'HobbyId': 7,
'HobbyName': 'Writing'
}],
"Skills": [],
"Language": [{
'Id': 7,
'Name': 'English'
}]
}
]
If there's a possible way to look like the table in the image with some css we can consider that too.
This is what I tried.
$(document).ready(function() {
var myArr = [{
"Id": 1,
"Name": 'Ken',
"Age": '30',
"Hobbies": [{
'HobbyId': 1,
'HobbyName': 'Swimming'
}, {
'HobbyId': 2,
'HobbyName': 'Reading'
}],
"Skills": [{
'SkillId': 1,
'SkillName': 'PHP'
}, {
'SkillId': 2,
'SkillName': 'MySQL'
}],
"Language": [{
'LangId': 2,
'LangName': 'English'
}, {
'LangId': 3,
'LangName': 'Chinese'
}]
},
{
"Id": 2,
"Name": 'Mike',
"Age": '20',
"Hobbies": [],
"Skills": [],
"Language": []
},
{
"Id": 3,
"Name": 'Charlie',
"Age": '25',
"Hobbies": [{
'HobbyId': 5,
'HobbyName': 'Dance'
}, {
'HobbyId': 6,
'HobbyName': 'Sing'
}, {
'HobbyId': 7,
'HobbyName': 'Writing'
}],
"Skills": [],
"Language": [{
'Id': 7,
'Name': 'English'
}]
}
];
var table = "<table border=1>";
for (var i = 0; i < myArr.length; i++) {
var arrHobies = myArr[i]['Hobbies'];
var arrSkills = myArr[i]['Skills'];
var arrLanguage = myArr[i]['Language'];
var rowspan = Math.max(arrHobies.length, arrSkills.length, arrLanguage.length);
console.log(rowspan);
table += "<tr>";
table += "<td rowspan=" + rowspan + ">" + myArr[i]['Id'] + "</td>";
table += "<td rowspan=" + rowspan + ">" + myArr[i]['Name'] + "</td>";
table += "<td rowspan=" + rowspan + ">" + myArr[i]['Age'] + "</td>";
console.log(arrHobies);
for (var j = 0; j < arrHobies.length; j++) {
if (j == 0) {
table += "<td>" + arrHobies[j]['HobbyId'] + "</td>";
table += "<td>" + arrHobies[j]['HobbyName'] + "</td>";
} else {
table += "<tr>";
table += "<td>" + arrHobies[j]['HobbyId'] + "</td>";
table += "<td>" + arrHobies[j]['HobbyName'] + "</td>";
//table+="</tr>";
}
//table+="</tr>";
}
for (var k = 0; k < arrSkills.length; k++) {
if (k == 0) {
table += "<td>" + arrSkills[k]['SkillId'] + "</td>";
table += "<td>" + arrSkills[k]['SkillName'] + "</td>";
} else {
// table+="<tr>";
table += "<td>" + arrSkills[k]['SkillId'] + "</td>";
table += "<td>" + arrSkills[k]['SkillName'] + "</td>";
table += "</tr>";
}
table += "</tr>";
}
table += "</tr>";
}
table += "</table>";
console.info(table);
$("#myDiv").html(table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv"></div>
guys i know its dummy question but i have spent alot of hours in this and still cant reach .. i want print the json content in table form .. here is my code
[{
"id": 1,
"name": "name1",
"age": 67,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 30,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 59,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 17,
"feedback": "feedback4"
}]
in javascript
$(document).ready(function() {
$.ajax({
url : 'data.json',
error : function(that, e) {
console.log(e);
},
success : function(data) {
$.each(data, function(index1, MyList) {
$.each(MyList, function(index2, item) {
$('body').append('<div id="div'+ index2+'" />');
$('#div' + index2).append(MyList[index2]);
});
});
}
});
});
here is my output
1234
name1name2name3name4
67305917
feedback1feedback2feedback3feedback4
and i want to make it in table form like this
1 name1 67 feedback1
2 name2 39 feedback2
3 name3 59 feedback3
4 name4 17 feedback4
try this snippet.you dont need two loops. just loop on items and build the bale row markup with data in each item.
data = [{
"id": 1,
"name": "name1",
"age": 67,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 30,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 59,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 17,
"feedback": "feedback4"
}]
var table_markyp = "<table>";
$.each(data, function(i, v) {
table_markyp += '<tr><td>' + v.id + '</td><td>' + v.name + '</td><td>' + v.age + '</td><td>' + v.feedback + '</td><tr>';
})
table_markyp += '</table>';
$('body').append(table_markyp)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
what you can do is , you have to create and HTML structure,
so that all the result will be displayed with a line by line and for that you can follow the table structure,.
check this code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
</body>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "data.json",
error : function(that, e) {
console.log(e);
},
success : function(data) {
var Mytable = "<table>";
$.each(data, function(temp, res) {
Mytable +=
'<tr>\n\
<td>' + res.id + '</td>\n\
<td>' + res.name + '</td>\n\
<td>' + res.age + '</td>\n\
<td>' + res.feedback + '</td>\n\
<tr>';
});
Mytable += '</table>';
$('body').append(Mytable);
}
});
});
</script>
</html>
create a container with an id e.g <div id="tablecontainer"> and this below will generate a table with the results
if you want headers you can take one object from data e.g data[0], perform Object.keys(data[0]) and attached them to a <tr/> <th/> object like the row method below
success: function(data) {
var container = $('#tablecontainer');
var table = $('<table></table>');
data.forEach(function(datarow) {
var row = $("<tr />");
for (var item in datarow) {
row.append($("<td>" + datarow[item] + "</td>"));
}
table.append(row);
});
container.append(table);
}
example output with headers:
var data = [{
"id": 1,
"name": "name1",
"age": 67,
"feedback": "feedback1"
}, {
"id": 2,
"name": "name2",
"age": 30,
"feedback": "feedback2"
}, {
"id": 3,
"name": "name3",
"age": 59,
"feedback": "feedback3"
}, {
"id": 4,
"name": "name4",
"age": 17,
"feedback": "feedback4"
}];
var container = $('body');
var table = $('<table></table>');
var head = $("<tr />");
var keys = Object.keys(data[0]);
keys.forEach(function(key){
head.append($("<th>" + key + "</th>"))
})
table.append(head);
data.forEach(function(datarow) {
var row = $("<tr />");
for (var item in datarow) {
row.append($("<td>" + datarow[item] + "</td>"));
}
table.append(row);
});
container.append(table);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>