I have written below code which creates a table inside another table from json response.
Main Table Code
var user = '<table width="98%" cellspacing="0" cellpadding="1" style="text-align: left; margin: 0 auto;';
user += 'border-collapse: collapse;" >';
$.each(html.ListOfReportModelData, function (key, val) {
user += '<tr>';
user += '<td>';
user += '<table width="100%" id="internalTable" border="0" cellspacing="2px" cellpadding="2px" >';
if (flag == "false") {
user += '<tr class="GreenColor">';
user += '<td style="width: 15%" class="accord">';
user += 'PR Number';
user += '</td>';
user += '<td style="width: 10%" class="accord">';
user += 'Created On';
user += '</td>';
user += '<td style="width: 10%" class="accord">';
user += 'Site Name';
user += '</td>';
user += '<td style="width: 10%" class="accord">';
user += 'Order ID';
user += '</td>';
user += '<td style="width: 55%" class="accord">';
user += 'File Name';
user += '</td>';
user += '</tr>';
}
var count = 0;
$.each(val.Orders, function (key, child) {
//debugger;
user += '<tr class="PinkColor">';
if (count == 0) {
user += '<td valign="top" rowspan="' + val.Orders.length + '" style="width: 15%"><a href="javascript:GetFinanceData(' + "'" + val.SiteName + "','" + val.Req_Number + "'" + ');">';
user += val.Req_Number;
user += '</a></td>';
count = 1;
}
user += '<td valign="top" style="width: 10%">';
user += val.CreatedDateText;
user += '</td>';
user += '<td valign="top" style="width: 10%">';
user += val.SiteName;
user += '</td>';
user += '<td valign="top" style="width: 10%">';
user += child.OrderId;
user += '</td>';
user += '<td style="width: 55%;break-word: word-wrap;">';
if (child.ShowLink) {
user += '<a href="javascript:Export(' + "'" + child.ID + "','" + val.SiteName + "'" + ');">';
}
user += child.Attachments_FileName;
if (child.ShowLink) {
user += '</a>';
}
user += '</td>';
user += '</tr>';
});
user += '<tr class="PinkColor">';
user += '<td colspan="5"><div id="' + val.Req_Number + '" ></div>';
user += '</td>';
user += '</tr>';
user += '</table>';
user += '</td>';
user += '</tr>';
flag = "true";
});
user += '</table>';
Child Table Creation
$.getJSON("/Home/FinancialInformation", data, function (html) {
totalRecords = html.FinanceData.length;
if (totalRecords == 0) {
$('#' + Req_Number + '').empty();
alert('No Finance Data Available!!!!!');
}
else {
var Fin = '<table id=' + Req_Number + ' width="100%" border="0" cellpadding="2px" cellspacing="2px" >';
Fin += '<tr class="GreenColor">';
Fin += '<td class="accord" style="width: 45%">Approval Type</td>';
Fin += '<td class="accord" style="width: 10%">Approval Required</td>';
Fin += '<td class="accord" style="width: 15%">Approved By</td>';
Fin += '<td class="accord" style="width: 10%">Approved By 521</td>';
Fin += '<td class="accord" style="width: 20%">Approved Date</td>';
Fin += '</tr>';
$.each(html.FinanceData, function (key, val) {
Fin += '<tr class="PinkColor">';
Fin += '<td style="width: 45%">' + val.Approval_Type + '</td>';
Fin += '<td style="width: 10%">' + val.Approval_Required + '</td>';
Fin += '<td style="width: 15%">' + val.Approved_By + '</td>';
Fin += '<td style="width: 10%">' + val.Approved_By_521 + '</td>';
Fin += '<td style="width: 20%">' + val.Approved_Date + '</td>';
Fin += '</tr>';
});
Fin += '</table>';
$('#' + Req_Number + '').empty()
$('#' + Req_Number + '').append(Fin);
}
});
I can see my table created correctly but I see lot of cumbersome activity in creating these codes.Is there better approach to achieve the same thing?Mostly using some plugins.
How others have said you should use a template engine like : handlebarsJS, mustacheJS, underscoreJS or maybe something like reactJS
Or if you want to keep it with jQuery, you can structure your code like :
Instead of injecting html directly like that, you can use jQuery syntax to create each element
You can split logic with functions
You can use only CSS classes(no style) and add it with jQuery
Here it's an example :
var getParentTable = function() {
// add style to CLASS in CSS
return $('<table></table>').addClass('parentTableClass');
};
var getInternalTable = function() {
return $('<table></table>')
.addClass('childTableClass')
.attr('id', 'internalTable');
};
var getRow = function(classValue) {
return $('<tr></tr>').addClass(classValue);
};
var getCol = function(textValue, classValue) {
return $('<td></td>')
.addClass(classValue)
.text(textValue);
};
var parentTable = getParentTable();
parentTable.append(internalTable);
$.each(html.ListOfReportModelData, function (key, val) {
var internalTable = getInternalTable();
var simpleRow = getRow();
var simpleCol = getCol();
var row1 = getRow('GreenColor');
var row3 = getRow('PinkColor');
row1
.append(getCol('PR Number', 'td1 accord'))
.append(getCol('Created On', 'td2 accord'))
.append(getCol('Site Name', 'td3 accord'))
.append(getCol('Order ID', 'td4 accord'))
.append(getCol('File Name', 'td5 accord'));
internalTable.append(row1);
$.each(val.Orders, function (key, child) {
var row2 = getRow('PinkColor');
.append(getCol(val.Req_Number, 'td1 accord'))
.append(getCol(val.CreatedDateText, 'td2 accord'))
.append(getCol(val.SiteName, 'td3 accord'))
.append(getCol(child.OrderId, 'td4 accord'))
.append(getCol(child.ShowLink, 'td5 accord'));
internalTable.append(row2);
});
internalTable.append(row3);
simpleCol.append(internalTable);
simpleRow.append(simpleCol);
parentTable.append(simpleRow);
});
Related
var serial_no = 1;
if (response.length > 0) {
for (var count = 0; count < response.length; count++)
{
html += '<tr>';
html += '<td>' + response[count].id + '</td>';
html += '<td>€' + response[count].inkoopprijs + '</td>';
html += '<td>€' + response[count].verkoopprijs + '</td>';
html += '<td>' + response[count].producten + '</td>';
html += '<td><a href="../prijswijzigen.php?edit=' + response[count].id + '" class="edit_btn">Edit</td>';
html += '<td><a href="C_R_U_D.php?del=' + response[count].id + '" class="del_btn">Delete</td>';
html += '</tr>';
serial_no++;
}
} else {
html += '<tr><td colspan="3" class="text-center">No Data Found</td></tr>';
}
document.getElementById('post_data').innerHTML = html;
document.getElementById('total_data').innerHTML = response.length;
I have this for code for a data table, I made this to support a search function, but I can figure out how to set a table length. I want to set it to ten.
I want to add Array elements to the table.
Array elements are dynamic coming from the database. And i am creating the Row for adding the one row from the generated data and appending rowAfter to add the other array elements
Here is the code i have written -
var rowSpan = 0;
var rowSpan1 = 0;
for (element in data)
{
// get products into an array
var productsArray = data[element].products.split(',');
var QuantityArray = data[element].quantity.split(',');
var ChemistArray = data[element].Retailername.split(',');
var PobArray = data[element].Pob.split(',');
rowSpan = productsArray.length;
rowSpan1 = ChemistArray.length;
var row = '<tr>' +
'<td rowspan="'+rowSpan+'">' + data[element].date + '</td>'+
'<td rowspan="'+rowSpan+'">' + data[element].doctor_name + '</td>';
// loop through products array
var rowAfter = "";
for (var i = 0; i < rowSpan; i++) {
if(i == 0) {
row += '<td>' + productsArray[i] + '</td>';
row += '<td>' + QuantityArray[i] + '</td>';
} else {
rowAfter += '<tr><td>' + productsArray[i] + '</td><td>' + QuantityArray[i] + '</td>';
}
}
for (var k = 0; k < rowSpan1; k++) {
if(k == 0) {
row += '<td>' + ChemistArray[k] + '</td>';
row += '<td>' + PobArray[k] + '</td>';
} else {
rowAfter += '<td>' + ChemistArray[k] + '</td><td>' + PobArray[k] + '</td> </tr>';
}
}
row +=
'<td rowspan="'+rowSpan1+'">' + data[element].locations +'</td>'+
'<td rowspan="'+rowSpan1+'">' + data[element].area + '</td>'+
'</tr>';
$('#tbody').append(row+rowAfter);
So as per the code I can finely display ProductArray and Quantity Array
And But i am not able to display the Chemist array after one another.
In the above Image i want to display data( Kapila and Kripa below the Chemist column) Some where making issue with tr and td.
Any help would really appreciated.
Data is a JSON Response -
In my case, ChemistArray(Retailername in response) contains 4 names and POBArray 4 values.
You need to add an empty <td></td> as a "placeholder".
for (element in data) {
var productsArray = data[element].products.split(',');
var quantityArray = data[element].quantity.split(',');
var chemistArray = data[element].Retailername.split(',');
var pobArray = data[element].Pob.split(',');
// find the largest row number
var maxRows = Math.max(productsArray.length, quantityArray.length, chemistArray.length, pobArray.length);
var content = '';
var date = '<td rowspan="' + maxRows + '">' + data[element].date + '</td>';
var doctorName = '<td rowspan="' + maxRows + '">' + data[element].doctor_name + '</td>';
var locations = '<td rowspan="' + maxRows + '">' + data[element].locations + '</td>';
var area = '<td rowspan="' + maxRows + '">' + data[element].area + '</td>';
content += '<tr>' + date + doctorName;
for (var row = 0; row < maxRows; row++) {
// only add '<tr>' if row !== 0
// It's because for the first row, we already have an open <tr> tag
// from the line "content += '<tr>' + date + doctorName;"
if (row !== 0) {
content += '<tr>';
}
// the ternary operator is used to check whether there is items in the array
// if yes, insert the value between the <td></td> tag
// if not, just add an empty <td></td> to the content as a placeholder
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>';
content += '<td>' + (quantityArray[row] ? quantityArray[row] : '') + '</td>';
content += '<td>' + (chemistArray[row] ? chemistArray[row] : '') + '</td>';
content += '<td>' + (pobArray[row] ? pobArray[row] : '') + '</td>';
// only add "locations + area + '</tr>'" if it is the first row
// because locations and area will span the whole column
if (row === 0) {
content += locations + area + '</tr>';
} else {
content += '</tr>';
}
}
$('#tbody').append(content);
}
content += '<td>' + (productsArray[row] ? productsArray[row] : '') + '</td>'; is just a short-hand for
content += '<td>';
if (productsArray[row]) {
content += productsArray[row];
} else {
content += '';
}
content += '</td>';
If there is item in the productsArray[row], let's say productsArray[0], which is 'Sinarest', then productsArray[row] would be truthy. Else, if there is no more products in the array, such as productsArray[3] will gives us undefined, which is a falsy value and the corresponding conditional will be ran.
In the below code i have used a json array(pedingPLT) to load data to below html table. here each an every table data has got a single value. in a particular table data i have included an button.so is there any possibility to assign multiple values to the button (*********), i mean by using an array. kindly help me
function TSC_document_status_list_table_for_tsc_portal() {
var tableData;
$.post("model/tscAdminView.php", {action: 'TSC_document_status_list_table_for_tsc_portal'}, function (e) {
if (e === undefined || e.length === 0 || e === null) {
tableData = '<tr class="error"><td colspan="4"> No Data Found in database </td></tr>';
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
} else {
$.each(e, function (index, pedingPLT) {
index++;
tableData += '<tr>';
tableData += '<td>' + index + '</td>';
tableData += '<td>' + pedingPLT.document_id + '</td>';
tableData += '<td>' + pedingPLT.tsc_accepted_Or_Created_date +'</td>';
tableData += '<td>' + pedingPLT.total_allocated_days + ' days' + '</td>';
tableData += '<td>' + pedingPLT.Expired_date + '</td>';
tableData += '<td> <button class="btn btn-sm btn-alt m-r-5 delete_selected_employee" value="' + ******** + '"><i class="fa fa-trash-o fa-lg"></i> </button>' + pedingPLT.total_quantity +'</td>';
tableData += '<td>' + pedingPLT.Completed_phone_list + '</td>';
tableData += '<td>' + pedingPLT.peding_phone_list + '</td>';
tableData += '</tr>';
});
//Load Json Data to Table
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
}
}, "json");
}
The value attribute of button is of type "text" (source), so it's not possible to add multiple values to it.
That said, you are free to stringify a JSON-string in it as value, and parse it when you need it:
JSON.stringify()
(method documentation: JSON.stringify)
You can use data-value attribute in the button and put the json string in the data-value attribute.
function TSC_document_status_list_table_for_tsc_portal() {
var tableData;
$.post("model/tscAdminView.php", {action: 'TSC_document_status_list_table_for_tsc_portal'}, function (e) {
if (e === undefined || e.length === 0 || e === null) {
tableData = '<tr class="error"><td colspan="4"> No Data Found in database </td></tr>';
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
} else {
$.each(e, function (index, pedingPLT) {
var button_data_value = '{"document_id" : pedingPLT.document_id , "total_days" : pedingPLT.total_allocated_days }';
index++;
tableData += '<tr>';
tableData += '<td>' + index + '</td>';
tableData += '<td>' + pedingPLT.document_id + '</td>';
tableData += '<td>' + pedingPLT.tsc_accepted_Or_Created_date +'</td>';
tableData += '<td>' + pedingPLT.total_allocated_days + ' days' + '</td>';
tableData += '<td>' + pedingPLT.Expired_date + '</td>';
tableData += '<td> <button class="btn btn-sm btn-alt m-r-5 delete_selected_employee" data-value= "'+JSON.Stringify(button_data_value)+'"><i class="fa fa-trash-o fa-lg"></i> </button>' + pedingPLT.total_quantity +'</td>';
tableData += '<td>' + pedingPLT.Completed_phone_list + '</td>';
tableData += '<td>' + pedingPLT.peding_phone_list + '</td>';
tableData += '</tr>';
});
//Load Json Data to Table
$('#TSC_document_status_list_table_for_tsc_portal tbody').html('').append(tableData);
}
}, "json");
}
I am trying to saved current updated row. My row contain select box and checkbox.If i change select box then selected value and checkbox status is updated.
function assignValue(itemsAll, itemLinked) {
var flage = true;
$.each(itemsAll, function (key, d) {
var tblRow = '<tr>';
tblRow += '<input id="hdnID" type="hidden" value="' + d.ItemCode + '" />';
tblRow += '<td style="width:20%"></span> ' + d.ItemCode + '</td>';
tblRow += '<td style="width:70%">' + d.ItemName + '</td>';
//alert("data"+d.Itme1);
if (itemPrice != null) {
var option = null;
for (var i = 0; i < itemPrice.d.length; i++) {
option += '<option value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
} else {
SessioExp(response.statusText);
}
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown">' + option + '</select></div></td>';
$.each(itemLinked, function (k, v) {
if (d.ItemCode == v.ITEMCODE) {
if (v.ISLINKED) {
tblRow += '<td style="width:10%" align="center"><span id="existingData" class="fa fa-times" aria-hidden="false" style="display: none;"></span></td>';
tblRow += '<td style="width:10%" align="center"><input type="checkbox" id="chkLinked" checked /></td>';
flage = false;
}
}
});
if (flage) {
tblRow += '<td style="width:10%" align="center"><span id="latestData" class="fa fa-check"></span></td>';
tblRow += '<td style="width:10%" align="center"><input type="checkbox" id="chkLinked"/></td>';
} else {
flage = true;
}
tblRow += '</tr>';
$("#tblStockTranslist tbody").append(tblRow);
});
}
Above code is set the row of table and my output is
Change id to class, as id must be unique in HTML like(for hidden field),
tblRow += '<input class="hdnID" type="hidden" value="' + d.ItemCode + '" />';
You can try onchange event like,
$('#tblStockTranslist').on('change','select,:checkbox',function(){
$tr = $(this).closest('tr');
code=$tr.find('.hdnID').val();
name=$tr.find('td:eq(1)').text();
value = !$(this).is(':checkbox') ? this.value : '';
// and so on...
console.log({code:code,name:name,value:value}); // make object like this
});
use this code
$("table").on("change","select",function()
{
var changed_row = $(this).parents("tr:eq(0)"),
selected_value = $(this).val();
});
Hi i have a javascript function that take the contents of a JSON file and the puts it in to a table, here is the code.
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
However what i need is to some formatting via if statements so for example
normally i would use something like the badly put together bunch of If statements.
if (Person.clock !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.Off !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
if (Person.on !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'lime';
}
if (Person.out !== false) {
document.getElementById('the cell where Person.Op is placed').style.backgroundColor = 'red';
}
However i am struggling to find the best way of putting what i already have with the function for creating the table and putting the formatting from the If statements together
what would be the best way to do this?
Why not add a class to each such case. something like this:
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<td>' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td class="'+(Person.clock? 'hasClock' : '') +'">' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
$(content).appendTo("tbody");
console.log(Person);
});
});
and then add a class to your css:
.hasClock{
background-color :lime;
}
$.getJSON("People.json",
function(data) {
$.each(data.People, function(i, PersonObj) {
var Person = PersonObj[Object.keys(PersonObj)[0]];
content = '<tr>';
content += '<tbody>';
content += '<td class="op ' + Person.Op + '">' + Person.Op + ' </td>';
content += '<td>' + Person.Name + ' </td>';
content += '<td>' + Person.WorkHours + ' </td>';
content += '<td>' + Person.Start + ' </td>';
content += '<td>' + Person.End + ' </td>';
content += '<td>' + Person.Clock + ' </td>';
content += '<td>' + Person.OFF + ' </td>';
content += '<td>' + Person.ON + ' </td>';
content += '<td>' + Person.OUT + ' </td>';
content += '</tr>';
content += '</tbody>';
content += '<p>';
$(content).appendTo("tbody");
console.log(Person);
});
});
Add class to your td's with the value. If you have definite values coming up, then you can create css selectors for that with the CSS properties you want.
Suppose you had value of op as someOpValue
You could write your css like foloowing.
td.op.someOpValue{
background : red;
}