When we call 1st time we get the start date of today.Then we wants to set new date and we want to keep the new set date after we call 2nd times.I don't know how to keep history data of date that we set and want to use again.
setCalendar: function() {
var inqYYYY = todate.substring(0, 4);
var inqMM = todate.substring(4, 6);
var inqDD = todate.substring(6, 8);
var inqStrDt = formatter.date(webank.date_minus(todate, 6));
var inqEndDt = inqYYYY + "-" + inqMM + "-" + inqDD;
datePicker.setCalendar("#inq_str_dt");
$("#inq_str_dt").val(inqStrDt);
datePicker.setCalendar("#inq_end_dt");
$("#inq_end_dt").val(inqEndDt);
}
You can set the inqStrDt and inqEndDt into a localStorage ( A persistent storage having lifetime till reset browser storage and history).
You can set the value by
localStorage.setItem('inqStrDt ', inqStrDt);
You can read accoringly as well
let startDate = localStorage.getItem('inqStrDt ');
if(startDate ) {
\\do something
}
Related
I'm creating an expense tracker application and wanted to get some insight on how to get and save a user's timestamp based on when they click the submit button.
let timestamp = new Date().getTime();
let todate = new Date(timestamp).getDate();
let tomonth = new Date(timestamp).getMonth() + 1;
let toyear = new Date(timestamp).getFullYear();
let original_date = tomonth + "/" + todate + "/" + toyear;
I understand the following code grabs the current date and formats it. If I were to just populate the DOM with original_date based on a click, then it'd work with today's date, but if I check it tomorrow, then it'll grab tomorrow's date. My current problem is, how would I go about saving the date based on a user's submit event without having it update to the current time.
Idea: Would having an event listener for the button be the way to go? Let's say:
function addTransaction(e) {
e.preventDefault();
let saveDate = original_date;
if (text.value.trim() === "" || amount.value.trim() === "") {
alert("Please add a description and amount of the transaction");
} else {
const transaction = {
id: generateID(),
text: text.value,
amount: +amount.value,
date: saveDate
};
transactions.push(transaction);
addTransactionDOM(transaction);
}
}
function addTransactionDOM(transaction) {
const sign = transaction.amount < 0 ? "-" : "+";
//creating new element
const item = document.createElement("li");
//Add class based on value
item.classList.add(transaction.amount < 0 ? "minus" : "plus");
item.innerHTML = `
${transaction.date}
${transaction.text}
${sign}${Math.abs(transaction.amount)}
`;
list.appendChild(item);
}
form.addEventListener("submit", addTransaction);
Would something like this work?
You can save in the browser localStorage the data you need to be retrieved later.
For example:
// Store data
localStorage.setItem('originalDateKey', original_date);
// Get data
var retrievedDate = localStorage.getItem('originalDateKey');
// Remove data
localStorage.removeItem('originalDateKey');
What you need is window.localStorage: localStorage documentation
window.localStorage.setItem(key, value) saves a string value to the user's local storage and can later be accessed with window.localStorage.getItem(key) where key is a unique string identifier.
Here's what I would do to achieve the desired result:
When the page is loaded, check if we have saved a previous date to localStorage
If saved date found, then load it from localStorage into the DOM
Set up a listener for the button which, saves the current date to localStorage (creating a new entry or overwriting the date that was there previously)
Here's some js flavored pseudo code:
// When site fully loaded, check for saved date and load into dom
window.addEventListener("load", function (event) {
const savedTimestamp = window.localStorage.getItem("savedDate");
// If savedTimestamp is null, then we have no previous saved date
if (savedTimestamp !== null) {
// Tip: we can reuse the date object instead of
// creating a new one every time here
const dateObj = new Date(savedTimestamp);
const todate = dateObj.getDate();
const tomonth = dateObj.getMonth() + 1;
const toyear = dateObj.getFullYear();
const savedDate = tomonth + "/" + todate + "/" + toyear;
// Show the saved date, just an example
// Put your code for showing the date here
showSavedDate(savedDate);
}
})
// ... rest of your code
function addTransaction(e) {
// ... omitting for brevity
let saveDate = original_date;
// ...
transactions.push(transaction);
addTransactionDOM(transaction);
// Save the current timestamp to local storage
window.localStorage.setItem("savedDate", saveDate);
}
// ... and so on
Make sure that saveDate is a string when you're saving it to localStorage, otherwise javascript will convert that to a string on its own and possibly screw things up.
Currently, I'm trying to find a way to track the changes of various cell changes with individual time stamps. I want to track changes so that every time one of these rows changes it marks a new time stamp in another column. I need to it to track every time that some make a change with a new time stamp in a new column.
Do you think someone could help me?
This is the function I am using and I was just going to set up a trigger to go off every day. I'm not sure this is the best way to track this type of change either so I am open to other suggestions if anyone has any. The only think is that an onEdit function DOESN'T work when you are using importrange for values. I put an example of the work I'm using here: https://docs.google.com/spreadsheets/d/1PLmkEmJ6sMeu1Y-8mEJ5FaSNIXVnzEuYrilFNA7G0Pk/edit#gid=464181309
.js I was trying to use:
function checkCompleted() {
var s = SpreadsheetApp.getActive().getSheetByName('Sheet1');
s.getRange('G2:H').getValues()
.forEach (function (r, i) {
if(r[0] == 'Completed' && !r[1])
s.getRange(i + 2, 8).setValue(new Date())
})
}
Change tracking Log
The problem with tracking changes by just changing the time stamp is that you only have knowledge of the last change to a given line. So I would suggest just writing a short message into a log entry that you can come back and read anytime. This will include a time stamp, spreadsheet name, sheet name, range changed, oldvalue and new value. You will need to create a file. I use Drive Notepad to create the file and I put all of these sorts of files in one data folder and you'll need the id of the data folder. You'll also need the id of your spreadsheet and the name of the sheet you wish to log the edits of.
You'll need to create an onEdit trigger for the onEditLog function.
The Code:
function onEditLog(e)
{
var ss=e.source.openById('SpreadsheetId');
var docnam=ss.getname();
var shtnam=ss.getActiveSheet().getName();
var range=e.range.getA1Notation();
if(docnam=='Your Document Name' && shtnam=='Sheet1')
{
var msg= 'Spreadsheet: ' + docnam + ' Sheet: ' + shtnam + + 'Range: ' + range + ' has been changed from ' + e.oldvalue + ' to ' + e.value;
logEntry1(msg,'filename');
}
}
function logEntry1(entry,file)//not you cannot run this function like other functions from your script editor. It must be run from an onEdit trigger so that it has access to the event object.
{
var file = (typeof(file) != 'undefined')?file:'eventlog.txt';
var entry = (typeof(entry) != 'undefined')?entry:'No entry string provided.';
if(entry)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'hh:mm:ss a");
var s = ts + ' - ' + entry + '\n';
saveFile(s, file, true);
}
}
//this function is taken from myUtility library you'll need to add your own DefaultFileName and DataFolderID.
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;//make change here. It is a string so put quotes around it.
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;//make other change here. Again it is a string
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}
the Question:
How can I use the API to return a boolean value if the date is a bank holiday?
I have done some research and found a great, and free API which contains bank holidays, however I am having trouble using it: http://holidayapi.com/
if i was to use this code:
var year = 2016;
var month = 3;
var day = 25;
var isAHoliday = false;
$.getJSON(
"http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day, function (data) {
console.log(data); //DOES NOT DISPLAY IN CONSOLE
if (data.holidays.length > 0) {
// BANK HOLIDAY
isAHoliday = true;
}
else {
//IS NOT BANK HOLIDAY
//AND NOTHING NEEDS TO BE DONE
}
});
i want to be able to return a true or false value depending on if this returns any data or not, however im doing something wrong as the getJSON request is not being called, please could someone correct me where i have gone wrong?
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=25 returns {"status":200,"holidays":[{"name":"Good Friday","country":"GB","date":"2016-03-25"}]}
http://holidayapi.com/v1/holidays?country=GB&year=2016&month=03&day=26 returns {"status":200,"holidays":[]}
it appears this is causing an issue: "http://holidayapi.com/v1/holidays?country=GB&year=" + year + "&month=" + month + "&day=" + day; if i pass one of the 2 URL's in above i get the correct result, I am having a play now with this
https://jsfiddle.net/dcxk6ens/
If you simply want to return a true value if the selected date is a holiday, or false if it is not, you could use a function like this:
(Please note that jsfiddle will not execute any AJAX calls to URLs using the "http://" protocol, since it is not secure.)
function isDateAHoliday(y, m, d) {
var jsonURL = "http://holidayapi.com/v1/holidays?country=GB&year=" + y + "&month=" + m + "&day=" + d;
var isAHoliday = false;
$.getJSON(jsonURL, function (data) {
// If the date is a holiday
if (data.holidays.length > 0) {
// Do some things
isAHoliday = true;
}
// Check values
console.log("JSON DATA: ", data);
console.log("Holiday?: " + isAHoliday);
return isAHoliday;
});
}
isDateAHoliday("2016", "3", "25");
If you wanted to return the name and country of the holiday as well, you could substitute isAHoliday = data.holidays[0]; inside of the if statement.
The holidays object must be called as a child of the returned data object:
Since the holidays object is an array you'll also need to use an index to access an item. Assuming there is at least one item returned, you would get the date like so:
var myDate = data.holidays[0].date;
However you should always check that there's at least one object in the array before getting the first one:
if(data.holidays.length > 0){...}
Incidentally, if all you want to do is check if there's a holiday on any particular day then this if statement is all you'll need, since an array length of more than zero means there's at least one holiday.
Edit
A full answer to your question, you could put this inside the .done() method:
var isAHoliday = false;
if(data.holidays.length > 0){
// There's at least one holiday today!
isAHoliday = true;
}
You don't have to declare a local variable, you'll probably use one that's declared elsewhere but that's up to you.
In the following code, I would like to save chrono time even when i reload the page. The variable to save as static is "diff". Because i need my chrono to return me the las time saved when i redirect to the same page. this code is declared in the header section. This code is not doing so, how would I accomplish that?
`
<script language="JavaScript">enter code here
var startTime = 0
var start = 0
var end = 0
var diff = 0
var timerID = 0
function chrono(){
end = new Date()
diff = end - start
diff = new Date(diff)
var msec = diff.getMilliseconds()
var sec = diff.getSeconds()
var min = diff.getMinutes()
var hr = diff.getHours()-1
if (min < 10){
min = "0" + min
}
if (sec < 10){
sec = "0" + sec
}
if(msec < 10){
msec = "00" +msec
}
else if(msec < 100){
msec = "0" +msec
}
//alert(document.getElementById("chronotime").innerText);
/* document.getElementById("pps").innerHTML = hr + ":" + min + ":" + sec + ":" + msec
document.getElementById("ppa").innerHTML = hr + ":" + min + ":" + sec + ":" + msec */
document.getElementById("chronotime").innerHTML = hr + ":" + min + ":" + sec + ":" + msec
timerID = setTimeout("chrono()", 10)
}
function chronoStart(){
start = new Date()
chrono()
}
function chronoContinue(){
start = new Date()-diff
start = new Date(start)
chrono()
}
function chronoReset(){
document.getElementById("chronotime").innerHTML = "0:00:00:000"
start = new Date()
}
function chronoStopReset(){
document.getElementById("chronotime").innerHTML = "0:00:00:000"
document.chronoForm.startstop.onclick = chronoStart
}
function chronoStop(){
document.chronoForm.startstop.value = "start!"
document.chronoForm.startstop.onclick = chronoContinue
document.chronoForm.reset.onclick = chronoStopReset
clearTimeout(timerID)
}
</script>
You can not keep a variable alive after refresh as variables are created in window which will get reloaded after refresh.
var a = 10;
//You can access this variable as below
console.log(a);//1st way
console.log(window.a);//2nd Way
So when the page gets refreshed, window gets reloaded.
Try to save your variables in the form of cookie(Old Traditional way)
document.cookie="key=value; key=value....."
Other options exists are:(Comparatively new.)
in browser "HTML5 Web SQL Database"(Reference).
But some time ago, I tested and it was not working on ff.
Local Storage. Below is the syntax:
localStorage.setItem("start", "10");
The options discussed above are for client side. The value can also be saved at server side.
Within the scope of a page, there is no way to have variables that survive page reloads. You could attempt browser storage, but that's risky (user may have multiple windows/tabs open with the same page, resulting in confusion).
The top option is to keep date information on the server in the user's session context (store timer start date when first request is received).
Having that in the user's session, you will be able to detect that the user's timer had already started upon subsequent calls.
This option also shields you from potential problems linked to multiple tabs (though not multiple/different browsers)
you can use browser's localStorage to achieve this action. As javascript does not work cross domain, either you should use localstorage or some back-end to achieve this functionality.
However when you use localStorage, the user can open up it's console and can use the command, localStorage.clear() to clear all browser's storage, so latter option is more reliable.
// Set value
localStorage.setItem(saveDiff, diff);
window.onload = function() {
//retrieve value back after page load
var saveDiff = localStorage.getItem(differenceValue);
}
I'm working on my first jQuery plugin which is a simple countdown timer with an option to set the target date. The goal is to get a plain text clock counting down to the provided target date & time. For the life of me I can't figure out how to use setTimeout or setInverval within the plugin so it actually counts down. Spent all day digging through stackoverflow and other sources but couldn't find a solution, so apologies if I'm just not getting it.
Here's what I've got:
(function( $ ){
$.fn.clock = function( options ) {
// ESTABLISH DEFAULTS
var settings = $.extend( {
'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss
}, options);
return this.each(function() {
// calculate milliseconds to target
tarDate = new Date(settings.target);
dateNow = new Date();
amount = tarDate.getTime() - dateNow.getTime();
delete dateNow;
// set label
label = settings.title;
// generate output
if(amount <= 0) {
out = '000:00:00:00';
} else {
td = 0; th = 0; tm = 0; ts = 0; out = ''; // reset everything
amount = Math.floor(amount/1000); // kill the milliseconds
td = Math.floor(amount/86400); // calculate days to target
amount = amount%86400; // convert amount to days
th = Math.floor(amount/3600); // calculate hours to target
amount = amount%3600; // convert amount to hours
tm = Math.floor(amount/60); // calculate minutes to target
amount = amount%60; // convert amount to minutes
ts = Math.floor(amount)+1; // calculate seconds to target
out += (td<=99?'0':'') + (td<=9?'0':'') + td + ':';
out += (th<=9?'0':'') + th + ':';
out += (tm<=9?'0':'') + tm + ':';
out += (ts<=9?'0':'') + ts;
}
// assemble and pump out to dom
$(this).html(out);
// set refresh rate
??????
});
};
})( jQuery );
Check out this link for an interesting pattern for plugin authoring. Basically what you need to do is provide a "method" for updating your clock:
(function( $ ){
function updateClock(element) {
var settings = element.data("settings");
// Your update logic goes here
}
$.fn.clock = function( options ) {
if ( options === 'update' )
return updateClock(this);
// Other methods, if any
else if ( typeof options !== 'object' )
throw 'Unknown method';
// ESTABLISH DEFAULTS
var settings = $.extend( {
'target' : '07/21/2013 09:00:00', // mm/dd/yyyy hh:mm:ss
}, options);
// Save your settings for later access
this.data("settings",settings);
Then, every time you want to update an element, you call it this way:
$(yourselector).clock("update");
(from outside; if updateClock is accessible from your scope, you can call it directly for efficiency. Just remember to wrap the element in $() if necessary)
Lastly, you have to configure setTimeout or setInterval. I would prefer setTimeout, because that will allow you to stop or restart your clock if necessary. Add this to the end of your updateClock, maybe preceeded by a check:
setTimeout(function() { updateClock(element); }, settings.refreshRate);
i believe you have to have setTimeout inside the function that needs to be called and have setTimeout call the function its in. then have a condition setup so once it reaches zero clearTimeout will go off http://jsfiddle.net/qUYQN/