I am currently learning JavaScript through some tutorials and this example came out in the tutorial.
I'm just confused why must the if statement be there.
I tried erasing the if statement and it still worked. Can someone help me please.
var timesVisited=0;
var dateVisited = 'Never';
if(localStorage.myLastVisit){
var visit = JSON.parse(localStorage.myLastVisit);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
}
$("#dateVisit").html(dateVisited);
timesVisited++;
$("#numVisit").html(timesVisited);
var myVisits = {};
myVisits.numVisits = timesVisited;
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
myVisits.dateVisits = hours + ':' + minutes;
localStorage.myLastVisit = JSON.stringify(myVisits)
I tried erasing the if statement and it still worked.
Only if myLastVisit is already in localStorage. If it isn't there (which is what the if is testing for), without the if you'll get an error from JSON.parse because you'll pass undefined into it, which will get converted to a string with the charactersundefined in it because JSON.parse requires a string, which will then fail because that's not valid JSON. The if is there so that if the setting isn't present, the default values assigned to timesVisited and dateVisited are used.
Works if the setting is there:
var timesVisited=0;
var dateVisited = 'Never';
var visit = JSON.parse(`{"numVisits": 2, "dateVisits": "2020-03-27"}`);
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited); // 2
console.log(dateVisited); // "2020-03-27"
Fails if it isn't:
var timesVisited=0;
var dateVisited = 'Never';
var visit = JSON.parse(undefined); // ERROR
timesVisited = visit.numVisits;
dateVisited = visit.dateVisits;
console.log(timesVisited);
console.log(dateVisited);
Related
var d = new Date();
var gunler= ["Pazar","Pazartesi","Salı","Çarşamba","Perşembe","Cuma","Cumartesi"];
document.getElementById("gun").innerHTML = gunler[d.getDay()];
var ic = document.getElementsByClassName("i");
var dis = document.getElementsByClassName("d");
var ll = document.getElementById("seciligun");
var ll2 = ll.innerHTML;
alert(ll2);
d.setFullYear(ll2);
var a=0;
while(a<ic.length){
if(gunler[d.getDay()]=="Cumartesi"||gunler[d.getDay()]=="Pazar"){
ic[a].innerHTML="";
}
else{
dis[a].innerHTML="";
}
a=a+1;
}
I using these codes in my js file , i taking date in my div tag that id = seciligun. When i use alert it seems like this : 2020-08-15 but when i say alert(d) , browser saying "invalid date". If i write like this d.setFullYear(2020-08-15) everything works correctly but i need use tag's value that id = seciligun.
You need to extract the year from ll2.
var y = ll2.split('-')[0];
d.setFullYear(y);
This question already has answers here:
Load scripts inside innerHTML [duplicate]
(2 answers)
Closed 4 years ago.
I have an HTML page that loads within another HTML page via innerHTML. After several days of work, this script works fine and another JS file is called for the interior page, a file (named "Unified_app.js") that basically runs some date calculations. Everything is working fine and the correct dates print to the console. However, I can't figure out on the page within a page can display the console dates. Document.write does not work in this situation (I'm assuming because of the tags are not read properly?), so I need to come up with a workaround. Any ideas?
This is the innerHTML functions as I have them:
function getYearOffset(strCutoffDate, intYearOffset)
{
var datCurrentDate = new Date();
var intCurrentYear = datCurrentDate.getFullYear();
var intCurrentMonth = strCutoffDate.substr(5, 2) - 1;
var intCurrentDay = strCutoffDate.substr(8, 2);
var datCutoffDate = new Date(intCurrentYear, intCurrentMonth, intCurrentDay);
if (Number(datCurrentDate) < Number(datCutoffDate))
{
var datRequestedDate = new Date(datCurrentDate.getFullYear(), intCurrentMonth, intCurrentDay);
}
else
{
var datRequestedDate = new Date(datCurrentDate.getFullYear() + intYearOffset, intCurrentMonth, intCurrentDay);
}
return datRequestedDate.getFullYear();
}
var script = document.createElement("script");
script.src = "/resource/resmgr/scripts/Unified_app.js";
document.head.appendChild(script);
function getInclude(strIncludeContainer, strIncludeURL)
{
var strPage = '';
var intIndexOfBodyOpen = 0;
var intIndexOfBodyClose = 0;
var objXhttp;
objXhttp = new XMLHttpRequest();
objXhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
strPage = this.responseText;
intIndexOfBodyOpen = strPage.indexOf('<body>');
intIndexOfBodyClose = strPage.indexOf('</body>');
document.getElementById(strIncludeContainer).innerHTML = strPage.substring(intIndexOfBodyOpen + 6, intIndexOfBodyClose);
}
};
objXhttp.open("GET", strIncludeURL, true);
objXhttp.send();
}
I'm using:
<script>document.write(award_year1);</script>
to write the following date calls:
const date = new Date();
let offset = 0;
const threshold = new Date();
threshold.setMonth(3); //January is 0!
threshold.setDate(3);
if (Date.now() > threshold) {
offset = 1;
}
var theDate = new Date();
var award_year1 = date.getFullYear() + offset;
var award_year2 = date.getFullYear() + 1 + offset;
console.log(award_year1);
console.log(award_year2);
When loading the page-within-a-page HTML file or the interior page itself I get the correct date calculations sent to the console, but I can't seem to get them to print within the innerHTML page when loaded into the other page. Any ideas you could send me down the right path? This is probably beyond my level of understanding of JavaScript. I thought perhaps my code was not in the correct order but I've been fiddling with this and can't seem to figure out where or why.
I'm not sure if this will solve the problem but you can try it.
As you said the document.write will not be triggered cause your JS is loaded before your DOM is.
document.addEventListener("DOMContentLoaded", function(event) {
//your functions
});
Maybe this will help you out
I guess this is just not possible. I ended up replacing the innerHTML with an iframe and that seems to have worked so that I can now use script tags. Not an ideal solution but it works
I have an .innerHTML statement that isn't working correctly, but only while within an if statement.
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
is the code that I'm using, and it's within this.
<script type="text/javascript">
var thedate - new Date();
var hourofday = thedate.getHours();
if(hourofday == 0) {
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
}
</script>
While outside of the if statement, the code works completely fine, however, inside the if statement it refuses to work. Even if I change the condition to just a plain true, the code still will not execute. I'm new to javascript, and I can't seem to find any error after looking for a couple hours. If it helps at all, the music player I'm using is at Billy Tumblr Audio Player.
I think you have added not just the if condition but also the code related to date calculation.
There you have a syntax error, used - instead of =. In your browser console you should see an error like Uncaught SyntaxError: Unexpected token -
var thedate = new Date();
// ^ = not -
var hourofday = thedate.getHours();
if (hourofday == 0) {
document.getElementById("music").innerHTML = "[MUSICPLAYERCODE]";
}
var thedate - new Date(); ?
Change it to:
var thedate = new Date();
You can try like this.
window.onload=function(){
var thedate = new Date();
var hourofday = thedate.getHours();
if(hourofday == 0) {
document.getElementById("music").innerHTML = "<H1>[MUSICPLAYERCODE]</H1>";
}
};
The code seems to work fine when inputting numbers 1-9 but anything above doesn't work, what could be the issue? Here is the code:
var varkString = prompt('Enter your VARK scores - [visual|aural|read|kinesthetic]','9|3|11|10');
var subStrings = varkString.split('|');
var visual = varkString[0];
var aural = varkString[1];
var read = varkString[2];
var kinesthetic = varkString[3];
var varkBar = 30*visual
document.writeln('<img src="bar_blue.png" width='+varkBar+' height="25"/>');{
}
Edit: Solved
You are parsing first character when you are getting visual, second on aural and third on read.
I belive that you want to use subStrings
var visual = subStrings[0];
var aural = subStrings[1];
var read = subStrings[2];
when you are slpiting the string varkString the array will automatically constructed and assigned to subStrings.so use it like this:
var subStrings = varkString.split('|');
var visual = subStrings[0];
var aural = subStrings[1];
var read = subStrings[2];
var kinesthetic = subStrings[3];
UiApp has DateBox and DateTimeFormat
for that Class. However, there is no such thing as TimePicker or TimeBox, where a user could enter a time in a well-specified manner such as through using Google Forms:
Forms has different behavior for this Widget in Chrome vs Firefox (I much prefer the Chrome behavior). Anyway, currently I am using a TextBox to get time values, where someone would enter a time value in the following manner:
12:00 or 13:50, etc. These times would be in the 24-hour clock so that I could create new Date objects based on someDate + " " + startTime, which would act as the real start time for an event on the Calendar (this is the process I currently use in several of my applications at work). This is obviously unreliable for several reasons.
Ex: If the user entered anything except a valid 24-hour representation in HH:MM:SS, Date creation would fail.
I don't want to force my boss to be overly-precautious about how he inputs times into the UI, and I also want to avoid regexing "valid" formats and having the UI do a lot of back-end work (it would be 18 regex tests total, and if any failed I'd have to handle them individually).
So, the question: is there an efficient/preferred method of getting times in UiApp, either via TextBox or some other interface?
What about something like that ? Test app here (updated with new version, see edit)
code below :
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'15px'});
var handler = app.createServerHandler('setTime').addCallbackElement(frame);
var h = app.createListBox().setId('h').setName('h').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m').setName('m').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am').setName('am').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setName('date').addValueChangeHandler(handler);
var label = app.createHTML('<b>StartTime *</b><br>When your reservation starts').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'10px'});
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'5px'});
var result = app.createHTML().setId('date').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'color':'#AA6','padding-top':'20px'})
.setHTML(Utilities.formatDate(new Date(new Date().setHours(0,0,0,0)), Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
frame.add(date).add(label).add(subFrame).add(result);
subFrame.add(h).add(m).add(am);
return app.add(frame);
}
function setTime(e){
var app = UiApp.getActiveApplication();
var date = app.getElementById('date')
var date = new Date(e.parameter.date);
var am = e.parameter.am
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter.h)+am;
var m = Number(e.parameter.m);
date.setHours(h,m,0,0)
Logger.log(date);
app.getElementById('date').setHTML(Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
return app
}
EDIT : here is the wrapped version and a demo with a grid and 10 panels.
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var grid = app.createGrid(10,2)
var handler = app.createServerHandler('setTime').addCallbackElement(grid);
var varName = 'date';
var htmlString = '<b>StartTime *</b> When your reservation starts'
for(var idx=0 ; idx<10;idx++){
var frame = pickDate(idx,varName,htmlString,handler);
grid.setText(idx, 0, 'test widget '+idx+' in a grid').setWidget(idx,1,frame);
}
var result = app.createHTML('<h1>Click any widget</h1>').setId('result');
return app.add(grid).add(result);
}
/* wrapped version
** takes a var name + index + label string + handler
** as input parameter
** The same handler will be used for every occurrence , the source being identified in the handler function (see code example below)
** and returns a selfcontained widget that you can add to a panel or assign to a grid
** or a flex Table
*/
function pickDate(idx,varName,htmlString,handler){
var app = UiApp.getActiveApplication();
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'1px', 'border-radius':'5px'});
var h = app.createListBox().setId('h'+idx).setName('h'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m'+idx).setName('m'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am'+idx).setName('am'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setId(varName+idx).setName(varName+idx).addValueChangeHandler(handler);
var label = app.createHTML(htmlString).setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'3px'}).setId('html'+idx);
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFE','padding':'1px', 'border-radius':'4px'});
frame.add(label).add(date).add(subFrame);
subFrame.add(h).add(m).add(am);
return frame;
}
function setTime(e){
// Logger.log(JSON.stringify(e));
var app = UiApp.getActiveApplication();
var idx = Number(e.parameter.source.replace(/\D+/,''));
Logger.log('date'+idx+ ' > '+e.parameter['date'+idx]);
var date = new Date(e.parameter['date'+idx]);
var am = e.parameter['am'+idx];
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter['h'+idx])+am;
var m = Number(e.parameter['m'+idx]);
date.setHours(h,m,0,0)
app.getElementById('result').setHTML('<h1>Widget Nr '+idx+' has value '+Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm')+'</h1>');
return app
}