How to populate a table with vertical and horizontal results? - javascript

HeaderA HeaderB HeaderA HeaderB
stuff 232 hey 3434
world 033 boy 221
bat 435 girl 930
This table is dynamic and gets populated live. Here's my JS code, but the logic is not working correctly. I need to tell it that every 2 columns is a new record, and make a new row every 4th column. Here's what I have so far:
function html_data(data) {
var html = '';
$.each(data, function (index, value) {
if ((index+1) % 4 == 0 && index != 0) {
html += '<td>'+value+'</td>';
html += '</tr>'
} else if ((index+1) % 5 == 0) {
html += '<tr>';
html += '<td>'+value+'</td>';
} else {
html += '<td>'+value+'</td>';
}
html += '</tr>';
});
return html;
}
Obviously the above code is completely wrong, but that's all I have so far. If I can the get the mod logic, I can fill in the blanks.

Try this http://jsfiddle.net/G3JK5/
HTML
<table id="table">
<tr>
<th>HeaderA</th>
<th>HeaderB</th>
<th>HeaderA</th>
<th>HeaderB</th>
<th>HeaderA</th>
<th>HeaderB</th>
</tr>
</table>
<input type="button" id="btn" value="Add some random data" />
Javascript
//Sample usage
var tbl = new weirdTable('table');
document.getElementById('btn').addEventListener('click', function(){
tbl.addData([
parseInt(Math.random() * 100),
parseInt(Math.random() * 100)
]);
});
weirdTable
function weirdTable(tableId){
var _me = null;
var _currentIndex = 0;
var _colCount = 0;
var _lastRowIndex = 0;
var construct = function(tableId){
_me = document.getElementById(tableId);
_colCount = _me.rows[0].cells.length;
_currentIndex = _colCount;
};
this.addData = function(data){
var row = _me.rows[_lastRowIndex];
//or var data = arguments;
for(var i = 0; i < data.length; i++){
if(_currentIndex >= _colCount){
_lastRowIndex++;
_currentIndex = 0;
row = _me.insertRow(_lastRowIndex);
}
row.insertCell(_currentIndex).innerText = data[i];
_currentIndex++;
}
};
construct(tableId);
}

Unless I'm missing something, you can just do this:
if (index%4===0) { // start of a row
html += '<tr>';
}
html += '<td>'+value+'</td>';
if (index%4===3) { // end of row
html += '</tr>';
}

Related

Change color of cells based on value in DB

I'm trying to accomplish the following.
I have a "grid" in which each cell can be 'owned' by a user.
To 'own' some new cells, the user should be able to click on two points (in a straight line) on the grid and then confirm by clicking on a button or cancel by clicking on another button, which updates the state of the grid. When both points are clicked, the cells between the two clicked ones must change color.
I should mention that I would like to achieve this only by using plain Javascript / PHP, if possible.
What I've done so far:
I have stored the 'grid' in a DB, having a record for each cell, containing position (i, j), owner and some other feature.
I query the DB using PHP, I save everything in memory (2D array - the grid is supposed to be small) and represent the grid by generating an HTML table
I'm trying to use JS to change the color of the cells when clicking, but I'm having problems (I'm new to JS and web programming in general).
I'm sure there's some kind of pattern to do what I want to do (surely is not rocket science), and would completely agree the following is pure Spaghetti code, but that's the only way I thought of doing it given my very very limited experience.
I do the following.
I have an HTML page with a named div in which I represent the table
<div id="Vis_table"> <?php echo $table ?> </div>
At the end of the body I have a script, which I report in its essential elements
var click = 0;
var grid = <?php echo json_encode($grid); ?>;
var Y_grid = <?php echo Y_g; ?>;
if (click == 0) { //first click
var cells = document.getElementsByTagName("th"); //take all cells
for (var i = 0; i < cells.length; i++) { // all rows
var row = parseInt(i / (Y_grid)); //dimensions
var col = i % (Y_grid);
cells[i].onclick = (function (xr, yc, index) {
return function () {
if (click == 0) { //first click, start
var tab = "<table>";
for (var x = 0; x < grid.length; x++) {
tab += "<tr>";
for (var y = 0; y < grid[0].length; y++) {
if (x == xr && y == yc) { //if it's the cell i clicked on
tab += "<th class = 'clicked'>" + x + " " + y + "</th>";
} else {
tab += "<th class = 'free'> </th>";
}
}
tab += "</tr>";
}
tab += "</table>";
click = 1;
document.getElementById("Vis_table").innerHTML = tab;
}
};
})(row, col, i);
}
}
Now, this works just fine, and the clicked cell changes color according to the CSS rules. The problem is that I don't know how to go on (ie color the cells between the first and the second clicked cells).
Do you have any suggestion?
Table prepared via JS(to do this in PHP is your task).
Area marking in JS :)
I've split the task in small steps to its easier to understand. If you got questions, feel free to ask!
/* This is generated by PHP (for testing i do it with js here) >>> */
var rows = 5;
var cols = 10;
var $table = $('#myTable');
for( let row = 1; row <= rows; row++ ) {
$row = $('<tr>');
for( let col = 1; col <= cols; col++ ) {
$col = $('<td>');
$col.text(row + "|" + col);
$col.attr('data-row', row);
$col.attr('data-col', col);
$row.append($col);
}
$table.append($row);
}
/* <<< */
var cells = [];
$('#myTable').click(function(e) {
$cell = $(e.target);
cells.unshift($cell);
if(cells.length > 2) {
cells.pop();
}
resetCells();
markActiveCells();
if ( cells.length == 2 ) {
fillArea();
}
});
function resetCells() {
$('#myTable td').removeClass('active');
$('#myTable td').removeClass('area');
}
function markActiveCells() {
$(cells).each(function() {
$(this).addClass('active');
});
}
function fillArea() {
if( cells.length < 2 ) return;
start_row_cell = (cells[0].data('row') <= cells[1].data('row'))?0:1;
start_col_cell = (cells[0].data('col') <= cells[1].data('col'))?0:1;
start_row = cells[start_row_cell].data('row');
end_row = cells[(start_row_cell+1)%2].data('row');
start_col = cells[start_col_cell].data('col');
end_col = cells[(start_col_cell+1)%2].data('col');
for( let row = start_row; row <= end_row; row++ ) {
for( let col = start_col; col <= end_col; col++ ) {
$('#myTable td[data-row=' + row + '][data-col=' + col + ']').addClass('area');
}
}
}
td {
font-size: 10px;
width: 25px;
height: 25px;
background-color: #EEE;
text-align: center;
}
td.active {
background-color: #FA0 !important;
}
td.area {
background-color: #FDA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable" cellspacing=0></table>

Jquery specify result loops on specific row of dynamic table header

I have difficulties in my projects...
I want to place the results from jquery loops into dynamic table (in specific month and year).
So first, I build the JSON and the results like this:
https://jsoneditoronline.org/?id=eb05e512b80a4995b3f6d0425b813dd9
Then I build the dynamic header from user desired filter:
months = (_ePYear - _sPYear) * 12;
months -= parseInt(_sPMonth);
months += parseInt(_ePMonth);
var html = '';
var counter = 0;
html = "<thead><tr>";
html += "<td>Subdomain</td>";
for(i; i <= months; i++) {
i %= 13
if (i == 0) {
//do nothing
} else {
if (i == 1 && counter != 0) {
_sPYear = parseInt(_sPYear)+1;
} else {
_sPYear = _sPYear;
}
html += "<td>"+_sPYear+' '+i+"</td>";
if (counter == months) {
break;
}
counter++;
}
}
html += "</tr></thead>";
$('#table-mrr-detail').append(html);
After that, I build body in jquery to process the results to the table:
//Build Body
var html2 = '';
var counter2 = 0;
months2 = (_ePYear2 - _sPYear2) * 12;
months2 -= parseInt(_sPMonth2);
months2 += parseInt(_ePMonth2);
html2 += "<tbody>";
$.each(json.data, function (i, ob) {
var me = this;
html2 += "<tr>";
html2 += "<td>"+this.subdomain+"</td>";
$.each(ob.data, function (ind, obj) {
for(i2; i2 <= months2; i2++) {
i2 %= 13
if (i2 == 0) {
//do nothing
} else {
if (i2 == 1 && counter2 != 0) {
_sPYear2 = parseInt(_sPYear2)+1;
} else {
_sPYear2 = _sPYear2;
}
console.log(this.month+'='+i2);
if (this.month == i2 && this.year == _sPYear2) {
html2 += "<td>"+this.amount+"</td>";
} else {
html2 += "<td>0</td>";
}
if (counter2 == months2) {
break;
}
counter2++;
}
}
});
html2 += "</tr>";
});
html2 += "</tbody>";
$('#table-mrr-detail').append(html2);
But, if you look at response in my json, the data of 'alim' subdomain have value in month 09, 10, 11 year 2017...
And... From the results above, The other subdomain is not showing anything (should show data based on json and specific header)...
Any help will appreciate...
Thanks...
EDIT
This is my init var:
var _sDate = $("input#idstartdate").val();
var _eDate = $("input#idenddate").val();
var _sPMonth = $("select#periodMonthStart :selected").val();
var _sPYear = $("select#periodYearStart :selected").val();
var _ePMonth = $("select#periodMonthEnd :selected").val();
var _ePYear = $("select#periodYearEnd :selected").val();
var _sPMonth2 = $("select#periodMonthStart :selected").val();
var _sPYear2 = $("select#periodYearStart :selected").val();
var _ePMonth2 = $("select#periodMonthEnd :selected").val();
var _ePYear2 = $("select#periodYearEnd :selected").val();
var _subdomain = $("input#subdomain").val();
var months = 0;
var months2 = 0;
var i = parseInt(_sPMonth);
var i2 = parseInt(_sPMonth);
I edited my current code from #shivaji, still no luck
The issue is with variable usage. You are modifying actual values, which is making your logic to fail, after a loop.
I have refactored the code to make it simple.
working code link: https://jsbin.com/fotezujupu/1/edit?html,js,output
var json = {"status":"success","data":[{"subdomain":"alim","data":[{"day":15,"month":9,"year":2017,"amount":"35025.97"},{"day":31,"month":10,"year":2017,"amount":"72387.01"},{"day":"01","month":11,"year":2017,"amount":"2335.06"}]},{"subdomain":"ql8","data":[{"day":7,"month":2,"year":2017,"amount":"925827.78"}]},{"subdomain":"Fathani","data":[{"day":27,"month":1,"year":2017,"amount":"231480.00"},{"day":28,"month":2,"year":2017,"amount":"240053.33"},{"day":31,"month":3,"year":2017,"amount":"265773.33"},{"day":30,"month":4,"year":2017,"amount":"257200.00"},{"day":31,"month":5,"year":2017,"amount":"265773.33"},{"day":"03","month":6,"year":2017,"amount":"25720.00"}]},{"subdomain":"asa4","data":[{"day":4,"month":10,"year":2017,"amount":"6010.03"},{"day":30,"month":11,"year":2017,"amount":"45075.21"},{"day":31,"month":12,"year":2017,"amount":"46577.72"},{"day":31,"month":1,"year":2018,"amount":"46577.72"},{"day":28,"month":2,"year":2018,"amount":"42070.19"},{"day":31,"month":3,"year":2018,"amount":"46577.72"},{"day":30,"month":4,"year":2018,"amount":"45075.21"},{"day":31,"month":5,"year":2018,"amount":"46577.72"},{"day":30,"month":6,"year":2018,"amount":"45075.21"},{"day":31,"month":7,"year":2018,"amount":"46577.72"},{"day":31,"month":8,"year":2018,"amount":"46577.72"},{"day":"21","month":9,"year":2018,"amount":"31552.65"}]},{"subdomain":"kenvapes-bpn","data":[{"day":15,"month":4,"year":2017,"amount":"85733.33"},{"day":31,"month":5,"year":2017,"amount":"177182.22"},{"day":30,"month":6,"year":2017,"amount":"171466.67"},{"day":31,"month":7,"year":2017,"amount":"177182.22"},{"day":31,"month":8,"year":2017,"amount":"177182.22"},{"day":"12","month":9,"year":2017,"amount":"68586.67"}]},{"subdomain":"ql7","data":[{"day":12,"month":1,"year":2017,"amount":"2388000.00"}]},{"subdomain":"demo-new","data":[{"day":28,"month":5,"year":2017,"amount":"13861.16"},{"day":30,"month":6,"year":2017,"amount":"14851.24"},{"day":31,"month":7,"year":2017,"amount":"15346.28"},{"day":31,"month":8,"year":2017,"amount":"15346.28"},{"day":30,"month":9,"year":2017,"amount":"14851.24"},{"day":31,"month":10,"year":2017,"amount":"15346.28"},{"day":30,"month":11,"year":2017,"amount":"14851.24"},{"day":"31","month":12,"year":2017,"amount":"15346.28"}]},{"subdomain":"fg32","data":[{"day":15,"month":9,"year":2017,"amount":"5200.00"},{"day":31,"month":10,"year":2017,"amount":"10746.67"},{"day":30,"month":11,"year":2017,"amount":"10400.00"},{"day":31,"month":12,"year":2017,"amount":"10746.67"},{"day":31,"month":1,"year":2018,"amount":"10746.67"},{"day":28,"month":2,"year":2018,"amount":"9706.67"},{"day":31,"month":3,"year":2018,"amount":"10746.67"},{"day":"28","month":4,"year":2018,"amount":"9706.67"}]},{"subdomain":"qol11","data":[{"day":3,"month":2,"year":2017,"amount":"59900.00"},{"day":31,"month":3,"year":2017,"amount":"618966.67"},{"day":30,"month":4,"year":2017,"amount":"599000.00"},{"day":"26","month":5,"year":2017,"amount":"519133.33"}]},{"subdomain":"pyusbyonline10","data":[{"day":27,"month":1,"year":2017,"amount":"113084.56"},{"day":28,"month":2,"year":2017,"amount":"117272.88"},{"day":31,"month":3,"year":2017,"amount":"129837.83"},{"day":30,"month":4,"year":2017,"amount":"125649.51"},{"day":31,"month":5,"year":2017,"amount":"129837.83"},{"day":30,"month":6,"year":2017,"amount":"125649.51"},{"day":31,"month":7,"year":2017,"amount":"129837.83"},{"day":31,"month":8,"year":2017,"amount":"129837.83"},{"day":30,"month":9,"year":2017,"amount":"125649.51"},{"day":31,"month":10,"year":2017,"amount":"129837.83"},{"day":30,"month":11,"year":2017,"amount":"125649.51"},{"day":31,"month":12,"year":2017,"amount":"129837.83"},{"day":31,"month":1,"year":2018,"amount":"129837.83"},{"day":28,"month":2,"year":2018,"amount":"117272.88"},{"day":31,"month":3,"year":2018,"amount":"129837.83"},{"day":30,"month":4,"year":2018,"amount":"125649.51"},{"day":31,"month":5,"year":2018,"amount":"129837.83"},{"day":30,"month":6,"year":2018,"amount":"125649.51"},{"day":31,"month":7,"year":2018,"amount":"129837.83"},{"day":31,"month":8,"year":2018,"amount":"129837.83"},{"day":30,"month":9,"year":2018,"amount":"125649.51"},{"day":31,"month":10,"year":2018,"amount":"129837.83"},{"day":30,"month":11,"year":2018,"amount":"125649.51"},{"day":"24","month":12,"year":2018,"amount":"100519.61"}]},{"subdomain":"oooop","data":[{"day":11,"month":9,"year":2017,"amount":"22335.59"},{"day":"17","month":10,"year":2017,"amount":"34518.64"}]},{"subdomain":"ql15","data":[{"day":9,"month":3,"year":2017,"amount":"17572050.00"}]},{"subdomain":"pyusbyonline12","data":[{"day":21,"month":1,"year":2017,"amount":"52342.50"},{"day":28,"month":2,"year":2017,"amount":"69790.00"},{"day":31,"month":3,"year":2017,"amount":"77267.50"},{"day":30,"month":4,"year":2017,"amount":"74775.00"},{"day":31,"month":5,"year":2017,"amount":"77267.50"},{"day":30,"month":6,"year":2017,"amount":"74775.00"},{"day":31,"month":7,"year":2017,"amount":"77267.50"},{"day":31,"month":8,"year":2017,"amount":"77267.50"},{"day":30,"month":9,"year":2017,"amount":"74775.00"},{"day":31,"month":10,"year":2017,"amount":"77267.50"},{"day":30,"month":11,"year":2017,"amount":"74775.00"},{"day":"05","month":12,"year":2017,"amount":"12462.50"}]},{"subdomain":"r1","data":[{"day":4,"month":1,"year":2017,"amount":"60268.16"},{"day":28,"month":2,"year":2017,"amount":"421877.09"},{"day":31,"month":3,"year":2017,"amount":"467078.21"},{"day":30,"month":4,"year":2017,"amount":"452011.17"},{"day":31,"month":5,"year":2017,"amount":"467078.21"},{"day":"25","month":6,"year":2017,"amount":"376675.98"}]},{"subdomain":"mam","data":[{"day":25,"month":9,"year":2017,"amount":"149833.33"},{"day":"05","month":10,"year":2017,"amount":"29966.67"}]},{"subdomain":"moirea","data":[{"day":29,"month":3,"year":2017,"amount":"497253.33"},{"day":30,"month":4,"year":2017,"amount":"514400.00"},{"day":31,"month":5,"year":2017,"amount":"531546.67"},{"day":30,"month":6,"year":2017,"amount":"514400.00"},{"day":31,"month":7,"year":2017,"amount":"531546.67"},{"day":"29","month":8,"year":2017,"amount":"497253.33"}]},{"subdomain":"pswdevsby14","data":[{"day":4,"month":10,"year":2017,"amount":"5384.27"},{"day":30,"month":11,"year":2017,"amount":"40382.02"},{"day":"24","month":12,"year":2017,"amount":"32305.62"}]},{"subdomain":"ql13","data":[{"day":10,"month":3,"year":2017,"amount":"169716.67"}]},{"subdomain":"dbj2017","data":[{"day":13,"month":1,"year":2017,"amount":"186272.98"},{"day":28,"month":2,"year":2017,"amount":"401203.34"},{"day":31,"month":3,"year":2017,"amount":"444189.42"},{"day":30,"month":4,"year":2017,"amount":"429860.72"},{"day":31,"month":5,"year":2017,"amount":"444189.42"},{"day":30,"month":6,"year":2017,"amount":"429860.72"},{"day":31,"month":7,"year":2017,"amount":"444189.42"},{"day":31,"month":8,"year":2017,"amount":"444189.42"},{"day":30,"month":9,"year":2017,"amount":"429860.72"},{"day":31,"month":10,"year":2017,"amount":"444189.42"},{"day":30,"month":11,"year":2017,"amount":"429860.72"},{"day":"12","month":12,"year":2017,"amount":"171944.29"}]},{"subdomain":"oke","data":[{"day":19,"month":10,"year":2017,"amount":"31350.00"},{"day":"11","month":11,"year":2017,"amount":"18150.00"}]},{"subdomain":"Fg24","data":[{"day":21,"month":3,"year":2017,"amount":"1986157.89"}]},{"subdomain":"ide2sen","data":[{"day":24,"month":1,"year":2017,"amount":"72281.56"},{"day":28,"month":2,"year":2017,"amount":"84328.49"},{"day":31,"month":3,"year":2017,"amount":"93363.69"},{"day":30,"month":4,"year":2017,"amount":"90351.96"},{"day":31,"month":5,"year":2017,"amount":"93363.69"},{"day":"05","month":6,"year":2017,"amount":"15058.66"}]},{"subdomain":"pswdevsby15","data":[{"day":26,"month":11,"year":2017,"amount":"103826.67"},{"day":"04","month":12,"year":2017,"amount":"15973.33"}]},{"subdomain":"ql5","data":[{"day":19,"month":1,"year":2017,"amount":"4907700.00"}]},{"subdomain":"pswdevjkt2","data":[{"day":23,"month":11,"year":2017,"amount":"122513.33"},{"day":"07","month":12,"year":2017,"amount":"37286.67"}]},{"subdomain":"cvabadidjajarukunsejahtera","data":[{"day":17,"month":4,"year":2017,"amount":"86775.56"},{"day":31,"month":5,"year":2017,"amount":"158237.78"},{"day":30,"month":6,"year":2017,"amount":"153133.33"},{"day":31,"month":7,"year":2017,"amount":"158237.78"},{"day":31,"month":8,"year":2017,"amount":"158237.78"},{"day":"10","month":9,"year":2017,"amount":"51044.44"}]},{"subdomain":"ql4","data":[{"day":12,"month":1,"year":2017,"amount":"9419333.32"}]},{"subdomain":"fg31","data":[{"day":28,"month":5,"year":2017,"amount":"56218.99"},{"day":30,"month":6,"year":2017,"amount":"60234.64"},{"day":31,"month":7,"year":2017,"amount":"62242.46"},{"day":31,"month":8,"year":2017,"amount":"62242.46"},{"day":30,"month":9,"year":2017,"amount":"60234.64"},{"day":"29","month":10,"year":2017,"amount":"58226.82"}]},{"subdomain":"PT-SAM","data":[{"day":4,"month":2,"year":2017,"amount":"68586.67"},{"day":31,"month":3,"year":2017,"amount":"531546.67"},{"day":30,"month":4,"year":2017,"amount":"514400.00"},{"day":31,"month":5,"year":2017,"amount":"531546.67"},{"day":30,"month":6,"year":2017,"amount":"514400.00"},{"day":"23","month":7,"year":2017,"amount":"394373.33"}]},{"subdomain":"Redia","data":[{"day":28,"month":1,"year":2017,"amount":"240053.33"},{"day":28,"month":2,"year":2017,"amount":"240053.33"},{"day":31,"month":3,"year":2017,"amount":"265773.33"},{"day":30,"month":4,"year":2017,"amount":"257200.00"},{"day":31,"month":5,"year":2017,"amount":"265773.33"},{"day":"02","month":6,"year":2017,"amount":"17146.67"}]},{"subdomain":"lotusbogalima","data":[{"day":10,"month":3,"year":2017,"amount":"171499.59"},{"day":30,"month":4,"year":2017,"amount":"514498.78"},{"day":31,"month":5,"year":2017,"amount":"531648.74"},{"day":30,"month":6,"year":2017,"amount":"514498.78"},{"day":31,"month":7,"year":2017,"amount":"531648.74"},{"day":"02","month":8,"year":2017,"amount":"34299.92"}]},{"subdomain":"pyusbyonline11","data":[{"day":21,"month":1,"year":2017,"amount":"17900.00"},{"day":28,"month":2,"year":2017,"amount":"23866.67"},{"day":31,"month":3,"year":2017,"amount":"26423.81"},{"day":30,"month":4,"year":2017,"amount":"25571.43"},{"day":31,"month":5,"year":2017,"amount":"26423.81"},{"day":30,"month":6,"year":2017,"amount":"25571.43"},{"day":31,"month":7,"year":2017,"amount":"26423.81"},{"day":31,"month":8,"year":2017,"amount":"26423.81"},{"day":30,"month":9,"year":2017,"amount":"25571.43"},{"day":31,"month":10,"year":2017,"amount":"26423.81"},{"day":30,"month":11,"year":2017,"amount":"25571.43"},{"day":31,"month":12,"year":2017,"amount":"26423.81"},{"day":31,"month":1,"year":2018,"amount":"26423.81"},{"day":28,"month":2,"year":2018,"amount":"23866.67"},{"day":31,"month":3,"year":2018,"amount":"26423.81"},{"day":30,"month":4,"year":2018,"amount":"25571.43"},{"day":31,"month":5,"year":2018,"amount":"26423.81"},{"day":30,"month":6,"year":2018,"amount":"25571.43"},{"day":31,"month":7,"year":2018,"amount":"26423.81"},{"day":31,"month":8,"year":2018,"amount":"26423.81"},{"day":"03","month":9,"year":2018,"amount":"2557.14"}]},{"subdomain":"pswtestsurabaya2","data":[{"day":6,"month":5,"year":2017,"amount":"12183.05"},{"day":"23","month":6,"year":2017,"amount":"46701.69"}]},{"subdomain":"damarsatu","data":[{"day":0,"month":1,"year":2017,"amount":"0.00"},{"day":28,"month":2,"year":2017,"amount":"800177.78"},{"day":31,"month":3,"year":2017,"amount":"885911.11"},{"day":30,"month":4,"year":2017,"amount":"857333.33"},{"day":31,"month":5,"year":2017,"amount":"885911.11"},{"day":"30","month":6,"year":2017,"amount":"857333.33"}]}]};
// Assuming your input fields are strings, so parsing them here itself.
var _sPMonth = parseInt('1');
var _sPYear = parseInt('2017');
var _ePMonth = parseInt('11');
var _ePYear = parseInt('2017');
var noOfMonths = ((_ePYear - _sPYear) * 12) - _sPMonth + _ePMonth + 1;
var columns = getColumns();
$('#table-mrr-detail').append(getTableHeaderHtml(columns));
$.each(json.data, function (sdI, subdomainItem) {
$('#table-mrr-detail').append(getRowHtml(subdomainItem));
});
function getColumns(){
var columns = [];
var counter = 0;
for(var i=0; i < noOfMonths; i++) {
var column = {};
column.month = ((_sPMonth + i -1) % 12) + 1;
column.year = parseInt((_sPMonth + i -1) / 12) + _sPYear;
columns.push(column);
}
return columns;
}
function getTableHeaderHtml(columns){
var html = "<thead><tr>";
html += "<td>Sub domain</td>";
$.each(columns, function(index, column){
html += "<td>"+column.year+' '+column.month+"</td>"
});
return html;
}
function getRowHtml(subdomainItem){
var html = "<tr>";
html += "<td>"+subdomainItem.subdomain+"</td>";
$.each(columns, function(index, column){
var obj = findByMonthAndYear(subdomainItem.data, column);
if (obj) {
html += "<td>"+obj.amount+"</td>";
} else {
html += "<td>0</td>";
}
});
return html;
}
function findByMonthAndYear(data, column){
for (var i=0; i < data.length; i++) {
if (data[i].year == column.year && data[i].month == column.month) {
return data[i];
}
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<table id="table-mrr-detail" class="table"></table>
</body>
</html>

Sum Total of Row and Column in HTML Table using Javascript Excluding First and Last

I'm trying to take an HTML table that was created from a Javascript 2D array and I am trying to get sum each row and column in the table excluding the top row and first TD in each row.
var pandlarray = [
[2017-04,0,-118.05,-181.21,-400.43,0]
[2017-05,1510.27,-35.34,-180.99,-351.46,0]
];
// BEGIN - Create HTML table from javascript array.
function makeTableHTML(myArray) {
var result = "<table id='pandltable'>";
result += "<tr><td>Month</td><td>Revenue</td><td>MaterialCost</td><td>Utilities</td><td>Labor</td><td>Margin</td></tr>";
for(var a=0; a<myArray.length; a++) {
result += "<tr>";
for(var j=0; j<myArray[a].length; j++){
if (myArray[a][j] === 0) {
result += "<td>"+0+"</td>";
}
else {
result += "<td>"+myArray[a][j]+"</td>";
}
}
result += "</tr>";
}
result += "<tr><td><strong>Total<strong></td><td></td><td></td><td></td><td></td><td></td></tr></table>";
return result;
}
document.write(makeTableHTML(pandlarray));
// END - Create HTML table from javascript array.
// BEGIN - Total row and columns for pandltable.
$("#pandltable tr:not(:first,:last) td:last-child").text(function(){
var t = 0;
$(this).prevAll().each(function(){
t += t += parseFloat($(this).text(),0) || 0;
});
return t;
});
$("#pandltable tr:last td:not(:first)").text(function(i){
var t = 0;
$(this).parent().prevAll().find("td:nth-child("+(i + 2)+")").each(function(){
t += parseFloat($(this).text(),0) || 0;
});
return t;
});
// END - Total row and columns for pandltable.
Not the most beautiful code I know but this is what I have to work with. The values that are returning right now to the total of each row and column are nowhere near right and they are also showing repeating decimals. Please help.
Made a few changes to your array definition and make table function. Assigned class 'first' to month column to prevent it being added in each row. And used .toFixed() function to limit totals to two decimal points. There is error in first function - calculate total for each row - t += t += -- this might be typo.
var pandlarray = ["2017-04,0,-118.05,-181.21,-400.43,0",
"2017-05,1510.27,-35.34,-180.99,-351.46,0"
];
// BEGIN - Create HTML table from javascript array.
function makeTableHTML(myArray) {
var result = "<table id='pandltable'>";
result += "<tr><td width='20%'>Month</td><td width='20%'>Revenue</td><td width='20%'>MaterialCost</td><td width='20%'>Utilities</td><td width='20%'>Labor</td><td width='20%'>Margin</td></tr>";
for(var a=0; a<myArray.length; a++) {
var thisRow = myArray[a].split(",");
result += "<tr>";
for(var j=0; j<thisRow.length; j++){
if (j === 0) {
result += "<td class='first'>"+thisRow[j]+"</td>";
}
else {
result += "<td>"+thisRow[j]+"</td>";
}
}
result += "</tr>";
}
result +="<tr><td colspan=6> </td> </tr>";
result += "<tr><td><strong>Total<strong></td><td></td><td></td><td></td><td></td><td></td></tr></table>";
return result;
}
document.write(makeTableHTML(pandlarray));
// END - Create HTML table from javascript array.
// BEGIN - Total row and columns for pandltable.
$("#pandltable tr:not(:first,:last) td:last-child").text(function(){
var t = 0;
$(this).prevUntil(".first").each(function(){
t += parseFloat($(this).text(),2) || 0;
});
t = t.toFixed(2);
return t;
});
$("#pandltable tr:last td:not(:first)").text(function(i){
var t = 0;
$(this).parent().prevAll().find("td:nth-child("+(i + 2)+")").each(function(){
t += parseFloat($(this).text(),0) || 0;
});
t = t.toFixed(2);
return t;
});
// END - Total row and columns for pandltable.

Populate html table with javascript array

I would like to fill an HTML table with a JavaScript array.
But, it doesn't work and I don't know why, my "innerHTML" is not interpreted.
My variable contains the good value, but when I do this :
document.getElementById("title").innerHTML = title;
It doesn't work.
This is my code:
var title = "";
var link = "";
var date = "";
var image = "";
function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "my_url");
xhr.onload = function () {
if (xhr.responseText == 0) {
alert("Vous n'avez poster aucun post");
} else {
var posts_array = JSON.parse(xhr.responseText);
for (var i = 0; i < posts_array.length; i++)
{
title = posts_array[i][0];
link = posts_array[i][1];
date = posts_array[i][2];
image = posts_array[i][3];
}
document.getElementById("title").innerHTML = title;
}
}
xhr.send();
}
This is my HTML :
<table id="posts">
<tr>
<th id="test">Titre</th>
<th>Lien</th>
<th>Date</th>
<th>Image</th>
</tr>
<tr>
<td id="title"></td>
<td id="link"></td>
<td id="date"></td>
<td id="image"></td>
</tr>
</table>
You're assigning the value of title inside your loop and then setting the innerHTML of an individual cell to title. Assuming your responseText is formatted correctly, the posts table will only ever contain the last element in your array. It seems like you need to create a new table row for each item in posts_array and add it to the posts table to get your intended result.
e.g.
var t = "";
for (var i = 0; i < posts_array.length; i++){
var tr = "<tr>";
tr += "<td>"+posts_array[i][0]+"</td>";
tr += "<td>"+posts_array[i][1]+"</td>";
tr += "<td>"+posts_array[i][2]+"</td>";
tr += "<td>"+posts_array[i][3]+"</td>";
tr += "</tr>";
t += tr;
}
document.getElementById("posts").innerHTML += t;
You have 3 errors in your code.
You overriding title, link, date and image on each iteration.
You setting only title, I think you want to set all data.
(Posible error) You setting only 1 post into table, probably you
want to see them all.
Easiest (and most common) way to create table from array is build HTML string (with table markup), and append it to table. Unfortunately IE do not support appending html into table, to solve this you may use jquery (it will create Elements from html and append them).
Example:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '<tr>';
for( var j = 0; j < columns.length; j++ ){
//create html table cell, add class to cells to identify columns
table_html += '<td class="' +columns[j]+ '" >' + posts_array[i][j] + '</td>'
}
table_html += '</tr>'
}
$( "#posts" ).append( table_html );
Another way is to use table dom api, this will not require jQuery:
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table = document.getElementById('posts');
for (var i = 0; i < posts_array.length; i++)
{
var row = table.insertRow( -1 ); // -1 is insert as last
for( var j = 0; j < columns.length; j++ ){
var cell = row.insertCell( - 1 ); // -1 is insert as last
cell.className = columns[j]; //
cell.innerHTML = posts_array[i][j]
}
}
It doesn't work for me.
I want to display wordpress posts into an HTML table.
My JS :
function get_posts() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "myUrl");
xhr.onload = function () {
if (xhr.responseText == 0) {
alert("Vous n'avez poster aucun post");
} else {
var posts_array = JSON.parse(xhr.responseText);
var columns = ['title', 'link', 'date', 'image']
var table_html = '';
for (var i = 0; i < posts_array.length; i++)
{
//create html table row
table_html += '<tr>';
for (var j = 0; j < columns.length; j++) {
//create html table cell, add class to cells to identify columns
table_html += '<td class="' + columns[j] + '" >' + posts_array[i][j] + '</td>'
}
table_html += '</tr>'
}
}
$("#posts").append(table_html);
}
xhr.send();
}
My HTML :
<table id="posts">
<tr>
<th id="test">Titre</th>
<th>Lien</th>
<th>Date</th>
<th>Image</th>
</tr>
</table>
My Web service (i'm using wordpress) :
global $current_user;
if(is_user_logged_in){
$current_user = wp_get_current_user();
}
$array = array();
$posts_array = array('author' => $current_user->ID, "post_type" => "alertes", "orderby" => "date", "order" => "DESC", "post_status" => "publish", "posts_per_page" => "10");
$posts = new WP_Query($posts_array);
if($posts->have_posts()){
while($posts->have_posts()){
$posts->the_post();
$post_array = array(get_the_title(), get_the_permalink(), get_the_date(), wp_get_attachment_url(get_post_thumbnail_id()));
array_push($array, $post_array);
}
echo json_encode($array);
}
else {
echo '0';
}

Javascript Letter Frequency Graph Using Google Charts API [Homework]

I have this assignment to enter a sentence in the textarea and then output it as a HTML Frequency Chart and then output it using the Google Chart API.
I was able to output it as the HTML Frequency Chart but I am stuck on the Google Chart API part.
At the bottom in the generateApiTable() function, I know the value for the seperate columns is being retrieved by the data.join() part but if I remove that, then I don't get the letters being displayed on the bottom. The default value being put in is always 5.
I already tried taking the for loops from the generateTable() function and put them in the generateApiTable() function and then replaced data.join() with myHeight but that only displayed the letter 'A' on x-axis with value 25 (which is correct) but I need the entire alphabet.
So my question is how would I go about populating the Google Chart Api image with the frequency values previously gotten (for the HTML table).
var image = new Image();
var frequency = new Array(26);
var letters = new Array(26);
function html_chart()
{
var table = document.getElementById("table");
input = document.getElementById("user_input").value
table.innerHTML = generateTable(input);
}
function api_table()
{
var table = document.getElementById("api_table");
table.innerHTML = generateApiTable();
}
function getCharacterCounts()
{
letters = {}
for (i = 0; i < input.length; i++)
{
console.log(letters[input[i]])
if (letters[input[i]] >= 0)
letters[input[i]] += 1
else
letters[input[i]] = 0
}
return letters
}
function generateTable(input) {
var Pos = 0;
var max = 0;
var myHeight = 0;
var newInput = input.toUpperCase();
for (i = 65; i < 91; i++)
{
frequency[Pos] = newInput.split(String.fromCharCode(i)).length - 1;
Pos++;
}
for (i = 0; i < frequency.length - 1; i++)
{
if (frequency[i] > max) {
max = frequency[i];
}
}
table = input + '<table>';
table += "<tr>";
table += "<td>Letter Frequency 100px</td>";
for (i = 0; i < frequency.length; i++)
{
myHeight = (frequency[i] / max) * 100;
myHeight = parseInt(myHeight, 10);
table += '<td height = "100" width = "10"><img src = "orange.gif" alt = "25" height = "' + myHeight + '" width = "5"></td>';
}
table += "</tr>";
table += "<tr>";
table += "<td></td>";
for (i = 65; i < 91; i++)
{
table += "<td>" + String.fromCharCode(i) + "</td>";
}
table += "</tr>";
table += "</table>";
return table;
}
function generateApiTable()
{
labels = []
data = []
for (i = 65; i < 91; i++)
{
data.push(5)
labels.push(String.fromCharCode(i))
}
return '<img src = "http://chart.apis.google.com/chart?cht=bvs&chd=t:' + data.join() + '&chs=717x100&chl='+labels.join("|") + 'A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z&chxt=y" />'
}
function eraseText()
{
document.getElementById("user_input").value = "";
}
EDIT
Html Code
<html>
<body>
<form>
<textarea name = "text" style = "width:400px; height:200px" id = "user_input">The Quick Brown Fox Jumped Over The Lazy Dogs</textarea><br>
<input type = "button" value = "HTML Chart" onclick ="html_chart()">
<input type = "button" value = "Reset Test Data" onclick= "eraseText()">
<input type = "button" value = "Image Chart" onclick = "api_table()">
</form>
<div id = "table">
</div>
<div id = "api_table">
</div>
<style>
td {
vertical-align:bottom;
horizontal-align:left;
padding:0;
text-align: center;
background-color: lightgrey;
}
</style>
</body>
<script type = "text/javascript" src = "code.js"/>
</script>
</html>

Categories