Reload the table along with as button get clicked - javascript
I'm working on code that I got via watching YouTube, It's an HR staff clock in and Clock out records, I've added additionally a table data in the HTML but It does not reload the table as the buttons are clicked ( we have to refresh the page to get the new records in the table), I searched for some articles and fount out this was helpful but I'm having some trouble to configure it. can I get some help to get this working?
My code
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('TimeTracker');
}
function getEmployees() {
var ss= SpreadsheetApp.getActiveSpreadsheet();
var employeeSheet = ss.getSheetByName("EMPLOYEES");
var getLastRow = employeeSheet.getLastRow();
return employeeSheet.getRange(2, 1, getLastRow - 1, 1).getValues();
}
function clockIn(employee) {
//DEFINE ALL ACTIVE SHEETS
var ss = SpreadsheetApp.getActiveSpreadsheet();
//DEFINE MAIN SHEET
var mainSheet = ss.getSheetByName("MAIN");
//LAST ROW ON MAIN SHEET
var lastRow = mainSheet.getLastRow();
//Define Return Variables
var return_date = '';
var error = 'SUCCESS';
var return_array = [];
for (var j = 2; j <= lastRow; j++)
{
// CHECK CLOCK IN
if(employee == mainSheet.getRange(j, 1).getValue() && mainSheet.getRange(j,3).getValue() == '')
{
error = 'Need to Clock Out before Clocking In';
return_array.push([error, return_date, employee]);
return return_array;
}
}
var new_date = new Date();
return_date = getDate(new_date);
// ADD CLOCK IN RECORD
mainSheet.getRange(lastRow+1,1).setValue(employee)
.setFontSize(12);
mainSheet.getRange(lastRow+1,2).setValue(new_date)
.setNumberFormat("MM/dd/yyyy hh:mm:ss am/pm")
.setHorizontalAlignment("left")
.setFontSize(12);
return_array.push([error, return_date, employee]);
return return_array;
}
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function getDate(date_in)
{
var currentDate = date_in;
var currentMonth = currentDate.getMonth()+1;
var currentYear = currentDate.getFullYear();
var currentHours = (addZero(currentDate.getHours()) > 12) ? addZero(currentDate.getHours()) - 12 : addZero(currentDate.getHours());
var currentMinutes = addZero(currentDate.getMinutes());
var currentSeconds = addZero(currentDate.getSeconds());
var suffix = (addZero(currentDate.getHours()) >= 12)? 'PM' : 'AM';
var date = currentMonth.toString() + '/' + currentDate.getDate().toString() + '/' +
currentYear.toString() + ' ' + currentHours.toString() + ':' +
currentMinutes.toString() + ':' + currentSeconds.toString() + ' ' + suffix;
return date;
}
function clockOut(employee) {
//DEFINE ALL ACTIVE SHEETS
var ss = SpreadsheetApp.getActiveSpreadsheet();
//DEFINE MAIN SHEET
var mainSheet = ss.getSheetByName("MAIN");
//LAST ROW ON MAIN SHEET
var lastRow = mainSheet.getLastRow();
var foundRecord = false;
var new_date = new Date();
var return_date = getDate(new_date);
var error = 'SUCCESS';
var return_array = [];
for (var j = 2; j <= lastRow; j++)
{
// FIND CLOCK IN RECORD
if(employee == mainSheet.getRange(j, 1).getValue() && mainSheet.getRange(j,3).getValue() == '')
{
// UPDATE CLOCK IN RECORD
mainSheet.getRange(j,3)
.setValue(new_date)
.setNumberFormat("MM/dd/yyyy hh:mm:ss am/pm")
.setHorizontalAlignment("left")
.setFontSize(12);
var totalTime = (mainSheet.getRange(j,3).getValue() - mainSheet.getRange(j,2).getValue()) /(60*60*1000);
mainSheet.getRange(j,4).setValue(totalTime.toFixed(2))
.setNumberFormat("#0.00")
.setHorizontalAlignment("left")
.setFontSize(12);
foundRecord = true;
}
}
// IF NO CLOCK IN RECORD
if(foundRecord == false)
{
return_array.push(['Need to Clock In First', '', employee]);
return return_array;
}
// CALL TOTAL HOURS
TotalHours();
return_array.push([error, return_date, employee]);
return return_array;
}
function TotalHours()
{
//DEFINE ALL ACTIVE SHEETS
var ss = SpreadsheetApp.getActiveSpreadsheet();
//DEFINE MAIN SHEET
var mainSheet = ss.getSheetByName("MAIN");
//LAST ROW ON MAIN SHEET
var lastRow = mainSheet.getLastRow();
//DEFINE ARRAY
var totals = [];
//LOOP THROUGH ALL RATES
for (var j = 2; j <= lastRow; j++)
{
var rate = mainSheet.getRange(j, 4).getValue();
var name = mainSheet.getRange(j, 1).getValue();
var foundRecord = false;
for(var i = 0; i < totals.length; i++)
{
//FOUND RECORD ADD TO TOTAL
if(name == totals[i][0] && rate != '')
{
totals[i][1] = totals[i][1] + rate;
foundRecord = true;
}
}
//ADD NEW RECORD, EXISTING RECORD NOT FOUND
if(foundRecord == false && rate != '')
{
totals.push([name, rate]);
}
}
//CLEAR DATA
mainSheet.getRange("F5:G1000").clear();
//DISPLAY TOTALS
for(var i = 0; i < totals.length; i++)
{
mainSheet.getRange(2+i,6).setValue(totals[i][0]).setFontSize(12);
mainSheet.getRange(2+i,7).setValue(totals[i][1]).setFontSize(12);
}
}
//Send Table to HTML
function doGet() {
return HtmlService
.createTemplateFromFile('TimeTracker')
.evaluate();
}
//Table Data
function getData() {
const headerColumns = 5; // In your case, the number of header columns is 5.
const sheet = SpreadsheetApp.openById('15Sb-g71H6-7PPey3aQROo-oCx_ULKQq2a5kIUeLEmNY').getSheetByName("TODAY");
const values = sheet.getRange(1, 1, sheet.getLastRow(), headerColumns).getDisplayValues();
console.log(values)
return values;
}
MY HTML out put
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"
integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
getEmployees();
});
function getEmployees()
{
google.script.run.withSuccessHandler(function(ar)
{
var employeeSelect = document.getElementById("employee");
console.log(ar);
let option = document.createElement("option");
option.value = "";
option.text = "";
employeeSelect.appendChild(option);
ar.forEach(function(item, index)
{
let option = document.createElement("option");
var employee = item[0];
option.value = item[0];
option.text = item[0];
employeeSelect.appendChild(option);
});
}).getEmployees();
};
function ClockIn()
{
$('#message').html("");
var employee = document.getElementById("employee").value;
if(employee != '')
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
ar.forEach(function(item, index)
{
if(item[0] == 'SUCCESS')
{
var message = item[2] + ' Clocked in at ' + item[1];
$('#message').html(message);
document.getElementById("message").className = "alert alert-primary";
}
else
{
var message = item[2] + ' ' + item[0];
$('#message').html(message);
document.getElementById("message").className = "alert alert-warning";
}
});
}).clockIn(employee);
}
}
function ClockOut()
{
$('#message').html("");
var employee = document.getElementById("employee").value;
if(employee != '')
{
google.script.run.withSuccessHandler(function(ar)
{
console.log(ar);
ar.forEach(function(item, index)
{
if(item[0] == 'SUCCESS')
{
var message = item[2] + ' Clocked out at ' + item[1];
$('#message').html(message);
document.getElementById("message").className = "alert alert-primary";
}
else
{
var message = item[2] + ' ' + item[0];
$('#message').html(message);
document.getElementById("message").className = "alert alert-warning";
}
});
}).clockOut(employee);
}
}
</script>
</head>
<body>
<div class="container">
<div style="padding: 10px;" >
<h1>WORK LOG</h1><br>
<form>
<div class="form-row">
<div class="form-group col-md-4">
<label for="employee">Employee</label>
<select class="form-control" id="employee">
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="button" value="Clock In" id="clockin" class="btn btn-primary" onclick="ClockIn()" />
<input type="button" value="Clock Out" id="clockout" class="btn btn-primary" onclick="ClockOut()" /><br><br>
<div class="alert alert-primary" role="alert" id="message">
</div>
</div>
</div>
</form>
</div>
<table class="table">
<? var [header, ...data] = getData(); ?>
<thead class="thead-dark"><tr>
<? for (var j = 0; j < header.length; j++) { ?>
<th><?= header[j] ?></th>
<? } ?>
</tr></thead>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
</div>
</body>
</html>
[1]: https://stackoverflow.com/questions/45864415/button-action-to-retrieve-data-from-spreadsheet-using-google-app-script
So the reason that you code is not working is because your not actually calling getData() on server side when either clockin or clockout buttons are clicked.
Related
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>
How to change this code to list post titles of all the post on Blogger in format YYYY.MM.DD <title> and chronological order?
I like to show my titles of posts on a specific page. It is more effective to get know what author have written than scroll all pages or navigate using archive widget. I found code (code is below) for generate list that sort post titles alphabetically but I like to show titles in chronological order. There is lot of code example about this but they are outdated. They doesn’t work anymore after some changes in blogger platform. How to change code to get post titles in chronological order and in format YYYY.MM.DD ? <div> <ul id="postList12"></ul> </div> <script type="text/javascript"> var startIndex = 1; var maxResults = 150; var allResults = []; function sendQuery12() { var scpt = document.createElement("script"); scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults; document.body.appendChild(scpt); } function printArrayResults(root) { //Sort Alphebetically allResults.sort(function(a, b) { var a_string = a.children[0].textContent ; var b_string = b.children[0].textContent ; if(a_string < b_string) return -1; if(a_string > b_string) return 1; return 0; }) var elmt = document.getElementById("postList12"); for (index = 0; index < allResults.length; index++) { elmt.appendChild(allResults[index]); } } function processPostList12(root) { var elmt = document.getElementById("postList12"); if (!elmt) return; var feed = root.feed; if (feed.entry.length > 0) { for (var i = 0; i < feed.entry.length; i++) { var entry = feed.entry[i]; var title = entry.title.$t; var date = entry.published.$t for (var j = 0; j < entry.link.length; j++) { if (entry.link[j].rel == "alternate") { var url = entry.link[j].href; if (url && url.length > 0 && title && title.length > 0) { var liE = document.createElement("li"); var a1E = document.createElement("a"); a1E.href = url; a1E.textContent = title + " (" + date.substr(0,10) + ")"; liE.appendChild(a1E); //elmt.appendChild(liE); allResults.push(liE); } break; } } } if (feed.entry.length >= maxResults) { startIndex += maxResults; sendQuery12(); } else { printArrayResults(); } } } sendQuery12(); </script> Code is copied from here: https://dansator.blogspot.fi/2015/10/general-alphabetical-list-of-posts.html
Remove sort method from the code. remove the following : //Sort Alphebetically allResults.sort(function(a, b){ var a_string = a.children[0].textContent ; var b_string = b.children[0].textContent ; if(a_string < b_string) return -1; if(a_string > b_string) return 1; return 0; }) Your code should be <div> <ul id="postList12"></ul> </div> <script type="text/javascript"> var startIndex = 1; var maxResults = 150; var allResults = []; function sendQuery12() { var scpt = document.createElement("script"); scpt.src = "/feeds/posts/summary?alt=json&callback=processPostList12&start-index=" + startIndex + "&max-results=" + maxResults; document.body.appendChild(scpt); } function printArrayResults(root) { var elmt = document.getElementById("postList12"); for (index = 0; index < allResults.length; index++) { elmt.appendChild(allResults[index]); } } function processPostList12(root) { var elmt = document.getElementById("postList12"); if (!elmt) return; var feed = root.feed; if (feed.entry.length > 0) { for (var i = 0; i < feed.entry.length; i++) { var entry = feed.entry[i]; var title = entry.title.$t; var date = entry.published.$t for (var j = 0; j < entry.link.length; j++) { if (entry.link[j].rel == "alternate") { var url = entry.link[j].href; if (url && url.length > 0 && title && title.length > 0) { var liE = document.createElement("li"); var a1E = document.createElement("a"); a1E.href = url; a1E.textContent = title + " (" + date.substr(0,10) + ")"; liE.appendChild(a1E); //elmt.appendChild(liE); allResults.push(liE); } break; } } } if (feed.entry.length >= maxResults) { startIndex += maxResults; sendQuery12(); } else { printArrayResults(); } } } sendQuery12(); </script>
Why is my elseif statement running everytime
I am building a form sending function in JavaScript, and I have run into a problem where it executes an else if statement every time. Here is my script: this.submit = function() { var url = this.url + "?"; for(el in this.elements) { var e = $(this.elements[el]); var n = this.names[el]; if(n === "submit") { window.alert("submit"); } else { url += n + "="; } if(el == "#dropdown") { var options = e.children(); for(var i = 0; i < options.length; i++) { var option = $('#' + options[i].id); if(option.attr('selected')) { url += option.attr('name'); url += "&"; window.alert("dropdown worked"); break; } } } else if(el != "#submit") { url += e.attr('value'); url += "&"; window.alert("input worked"); } } window.location.href = url; }; The problem being that the else if(el != "#submit"){} runs even when the id in question is "#submit". Does anyone know why this doesn't work? To help, here is my php document, and the rest of the form constructer: php: <!DOCTYPE html> <html> <head> <title>Test</title> <script src="http://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <?php if(!$_GET): ?> <form id="form1"> <input type="text" id="input1" name="name"/> <br> <select id="dropdown" name="color"> <option id="null" name="null"></option> <option id="opt1" name="blue">blue</option> <option id="opt2" name="yellow">yellow</option> </select> <br> <button type="submit" id="submit" name="submit"onclick="form1.submit()">Submit data</button> </form> <script src="http://charlie/form.js"></script> <script> var form1 = new form("form1"); form1.setElements(); form1.logElements(); </script> <?php elseif(!(isset($_GET['name']) || isset($_GET['color']))): ?> <p style="color:red">ERROR! form.js failed</p> <?php else: ?> <p><?= $_GET['name'] ?></p> <p><?= $_GET['color'] ?></p> <?php endif; ?> </body> </html> form constructer: function form(id) { this.id = "#" + id; this.url = window.location.href; this.elements = []; this.names = []; this.setElements = function() { var elements = [],names = [],children = $(this.id).children(); for(var i = 0; i < children.length; i++) { var childid = children[i].id; if(childid) { elements.push('#' + childid); } } this.elements = elements; for(var e in this.elements) { names.push($(this.elements[e]).attr('name')); } this.names = names; }; this.logElements = function() { for(var e in this.elements) { console.log(this.elements[e]); } for(var n in this.names) { console.log(this.names[n]); } }; this.submit = function() { var url = this.url + "?"; for(el in this.elements) { var e = $(this.elements[el]); var n = this.names[el]; if(n === "submit") { window.alert("submit"); } else { url += n + "="; } if(el == "#dropdown") { var options = e.children(); for(var i = 0; i < options.length; i++) { var option = $('#' + options[i].id); if(option.attr('selected')) { url += option.attr('name'); url += "&"; window.alert("dropdown worked"); break; } } } else if(el != "#submit") { url += e.attr('value'); url += "&"; window.alert("input worked"); } } window.location.href = url; }; }
Turning my comment into an answer with some code. The "in" operator in Javascript iterates over properties not the elements at each index. To make your current code work, change the code to the following: var el; var elementCount = this.elements.length; for (var i = 0; i < elementCount; i++) { el = this.elements[i]; This will produce the expected behavior.
The for...in loop is the cause. el tkaes the values 0, 1, 2 ...you need to compare this.elements[el] instead of el : if(this.elements[el] == "#dropdown") ... else if(this.elements[el] != "#submit") { ...
How to show message in for-loop issues in javascript or using jquery
I tried this for almost two days but still nothing. Maybe someone can help who is highly skilled in javascript loops. I have this code: $(function(){ var len = $('#groupContainer > div').length; var arr = []; for(var i=0; i < len; i++){ var number = $('#number_' + [i + 1]); var date = $('#date_' + [i + 1]); var count = i + 1; var message =""; console.log(number) var a = number.map(function(){ return this.value; }); var b = date.map(function(){ return this.value; }); var newObj = {number: a[0], date: b[0]} arr.push(newObj); } var message = ""; for(var c = 0; c < arr.length; c++) { for(var d in arr[c]) { message += 'Group: ' + [c + 1] + '\n'; if(arr[c].hasOwnProperty(d)) { if(arr[c][d] == "") { message += d + ' is required!\n'; } } message = message + "\n"; } } alert(message); }); And the expected output: If all the fields in group 1 is filled and group 2 is not show alertbox: Group 2: Number is required! Date is required! If all field is not filled show: Group 1, 2 Number is required! Group 1, 2 Date is required! If all field is filled do nothing. Here's my FIDDLE
Your code here is too much complicated and should be simplified. You need to save the messages in an object and loop through them later to show the messages in order. var messages = {}; var message = ""; for(var c = 0; c < arr.length; c++) { var groupMessage = false; for(var d in arr[c]) { if(arr[c].hasOwnProperty(d)) { if(arr[c][d] == "") { if(messages[d]==undefined) { messages[d]={groups:[]}; } messages[d].groups.push(c+1); } } } var lastgroup = ""; for(i in messages) { m = messages[i]; if(m.groups.join(",")==lastgroup) { message = message.replace("Group "+m.groups.join(",")+" ","Group "+m.groups.join(",")+":\n"); message+=i+" is required!\n"; } else { message+="Group "+m.groups.join(",")+" "+i+" is required!\n"; } lastgroup = m.groups.join(","); } // ..... }
$(function(){ var len = $('#groupContainer > div').length; var arr = []; for(var i=0; i < len; i++){ var number = $('#number_' + [i + 1]); var date = $('#date_' + [i + 1]); var count = i + 1; var message =""; var a = number.map(function(){ return this.value; }); var b = date.map(function(){ return this.value; }); var newObj = {number: a[0], date: b[0]} arr.push(newObj); } console.log(arr); var message = ""; for(var c = 0; c < arr.length; c++) { haveErrorInGroup = false; for(var d in arr[c]) { if(arr[c].hasOwnProperty(d)) { if(arr[c][d] == "") { if(!haveErrorInGroup){ haveErrorInGroup= true; message += 'Group: ' + [c + 1] + '\n'; } message += d + ' is required!\n'; } } } } alert(message); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="groupContainer"> <div id ="profileGroup1"> <div class="item"> Number1: <input type="text" id="number_1" value="20"> </div> <div class="item"> Date1: <input type="text" id="date_1" value=""> </div> </div> <div id ="profileGroup2"> <div class="item"> Number2: <input type="text" id="number_2" value="2015-05-05"> </div> <div class="item"> Date2: <input type="text" id="date_2" value=""> </div> </div> </div>
Reload popup with information
I have a table in my popup and I save the values entered by a user to localStorage. Here are the snippets. popup.html <table id="main_table"> </table> <script src="popup.js"></script> popup.js function create_row() { localStorage["last_session"] = true; var table = document.getElementById("main_table"); var n = table.rows.length; var m = table.rows[0].cells.length; var row = table.insertRow(n); if (!localStorage['use_storage']) { if (n === 1) { localStorage["cells"] = JSON.stringify([{}]); } else if (n > 1) { var cells = JSON.parse(localStorage["cells"]); cells.push({}); localStorage["cells"] = JSON.stringify(cells); } } var cell = row.insertCell(0); cell.innerHTML = n; for (j=1; j<m; j++) { create_cell(n-1, j, row); } return row } function create_cell(i, j, row){ var cell = row.insertCell(j); if (j == 1) { cell.innerHTML = "<input size=10>"; } else { cell.innerHTML = "<input size=4>"; } cell.addEventListener("change", function () { var cells = JSON.parse(localStorage["cells"]); cells[i.toString()][j.toString()] = cell.childNodes[0].value; localStorage["cells"] = JSON.stringify(cells); }) } document.getElementById('create_row').onclick = create_row; // restore a table if (localStorage["last_session"]) { localStorage["use_storage"] = true; try { var cells = JSON.parse(localStorage["cells"]); var n = cells.length; var table = document.getElementById("main_table") for (i=0; i<n; i++) { var row = create_row(true); var cell = cells[i] for (var key in cell) { if (cell.hasOwnProperty(key)) { var col = parseInt(key); var val = cell[key]; row.cells[col].childNodes[0].value = val; } } } } catch (e) { console.log("Catched error"); console.log(e); } if (localStorage["results"]) { show_results(); } localStorage['use_storage'] = false; } In my browser it works as it is supposed, that is after refreshing a page popup.html I have the state where I left (number of rows and values are preserved). However, in my chrome extension, after clicking to any area and thus reloading the extension, I have the initial empty table. How can I preserve the table in this particular case?