The script I wrote has a button that, when clicked, should show year and IP address, but it does automatically. I saw in another 3D that this issue comes when in the "onclick" option you put a function like
<button name="bottone" onclick=myFunction()>AH-AH</button>
but this is not my case.
<button name="bottone" onclick=myFunction>AH-AH</button>
<p id="demo"></p>
<script>
function myFunction(json) {
var d = new Date();
var n = d.getFullYear();
var ip = json.ip;
document.getElementById("demo").innerHTML = n + ' ' + ip;
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=myFunction"></script>
Seems like the second script "overrides" the option onClick.
The script calls your function immediately:
myFunction({"ip": "88.9.35.40", "address":"88.9.35.40"});
Instead, you could store the data in a variable, and use that variable in the event handler:
<button name="bottone">Display year and IP</button>
<p id="demo"></p>
<script>
(function() {
var ipData;
window.getIpData = function(data) { // We must use awful global for JSONP
delete window.getIpData; // Get rid of the awful global
ipData = data;
};
document.getElementsByName('bottone')[0].onclick = function() {
if(ipData) {
var year = new Date().getFullYear(),
ip = ipData.ip;
document.getElementById("demo").innerHTML = year + ' ' + ip;
}
}
})();
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getIpData"></script>
Change that onClick to onclick="myFunction()", that's how it should be (always use the quotes, it's a function call so include the parenthesis).
That second script invokes directly the function you are passing as callback parameter ?callback=myFunction, so it will call autonomously your myFunction().
Try opening that script url directly in your browser to see what the script will execute:
myFunction({"ip": "11.11.11.81", "address":"11.11.11.81"});
Use this piece of code. The script u included, was calling a callback fucntion, and inside that it was printing Date and Ip onload of page.
So I have kept that showing ip and date code in separate function.
The variable which are used for display of date and Ip> I made them global, so those variable can be used outside callback method.
<button name="bottone" onclick="showIpNDate()">AH-AH</button>
<p id="demo"></p>
<script>
var ip, n;
function myFunction(json) {
var d = new Date();
n = d.getFullYear();
ip = json.ip;
}
function showIpNDate() {
document.getElementById("demo").innerHTML = n + ' ' + ip;
}
</script>
<script type="application/javascript" src="http://jsonip.appspot.com/?callback=myFunction"></script>
Related
I am using:
document.write ("temperature is" + c.toString()) to get the calculation on the next page. I do understand that to put the history back button into the page I need to do this:
<button onclick="goBack()">Go Back</button>
<script>
function goBack() {
window.history.back();
}
</script>
but I cannot figure out how to get that into the new page that document.write loads when my function is executed.
Should I not be using document.write? Or how do I put it into my function?
Here is my entire function:
<script type="text/javascript">
function ToC() {
var f = parseFloat(strIn);
var c = (f - 32) * 5/9;
document.tempform.temp.value = c.toString();
}
document.write("Temperature is " + c.toString());
}
</script>
Write the button with document.write, but then add the click event afterwards.
document.write("<button id='back'>Go Back</button>");
document.getElementById('back').onclick=function(){
window.history.back();
};
Here's a demo:
https://jsfiddle.net/Lxx781dm/
If you are getting value for strIn variable then the only change required is below :
<script>
function ToC()
{
var f = parseFloat(strIn);
var c = (f - 32) * 5/9;;
document.tempform.temp.value = c.toString();
document.write("Temperature is " + c.toString())
}
</script>
Also you have to take care of below line as well :
document.tempform.temp.value = c.toString();
This line states that you want to save the value in a form having name tempform and an field having name temp, so you should have something like below in you page :
<form name="tempform">
<input type="text" name="temp" />
</form>
I'm attempting to send emails using an HTML template.
I've looked at this post:
(https://stackoverflow.com/questions/33178702/passing-variables-into-html-code)
Would either of the two code examples be close to something that could work to pass the variables from the Javascript to the HTML template?
My javascript variables are named detail2, detail3, detail4, detail5 and detail6.
1st attempt:
<html>
<head>
<script>
{
var detail2 = document.getElementById("detail2").innerHTML;
var detail3 = document.getElementById("detail3").innerHTML;
var detail4 = document.getElementById("detail4").innerHTML;
var detail5 = document.getElementById("detail5").innerHTML;
var detail6 = document.getElementById("detail6").innerHTML;
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
2nd attempt:
<html>
<head>
<script>
{
<input type="hidden" id="Detail2" value="detail2" />
<input type="hidden" id="Detail3" value="detail3" />
<input type="hidden" id="Detail4" value="detail4" />
<input type="hidden" id="Detail5" value="detail5" />
<input type="hidden" id="Detail6" value="detail6" />
}
}
</script>
</head>
<body>
<p>
<br>"Punctual? " document.getElementById('detail2').value<br>
<br>"Attention to detail? " document.getElementById('detail3').value<br>
<br>"Overall Professionalism? " document.getElementById('detail4').value<br>
<br>"Date of Service: " document.getElementById('detail5').value<br>
<br>"Notes/Details: " document.getElementById('detail6').value<br>
</p>
</body>
</html>
Finally, the method given on GAS Dev is below, but this only confuses me more. I am sure I've been at this too long and I'm burned out, I just can't seem to see the answer on this one.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<table>
<? 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>
</body>
</html>
If anyone can help it's much appreciated!
Below is the Javascript from the .gs script file.
function SendEmail() {
// initialize data
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getDataRange();
var values = range.getValues();
// iteration loop
for (var i = 1; i<values.length; i++) {
// current times for comparator
var month = new Date().getMonth(); // returns today as 0-11 -- Jan is 0
var day = new Date().getDate(); // returns today as 1-31
var hour = new Date().getHours(); // returns today as 0-23
var minute = new Date().getMinutes(); // returns today as 0-59
// pull data from spreadsheet rows
var company = values[i][0];
var rating = values[i][1];
var detail1 = values[i][2];
var detail2 = values[i][3];
var detail3 = values[i][4];
var detail4 = values[i][5];
var detail5 = values[i][6];
var sendTime = values[i][7];
// character send times for comparator
var cSendMonth = sendTime.getMonth(); // returns sendMonth as 0-11 -- Jan is 0
var cSendDay = sendTime.getDate(); // returns sendDay as 1-31
var cSendHour = sendTime.getHours(); // returns sendHour as 0-23
var cSendMinute = sendTime.getMinutes(); // returns sendMinute as 0-59
// comparator
if(cSendMonth == month) {
if(cSendDay == day) {
if(cSendHour == hour) {
if(cSendMinute == minute) {
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
MailApp.sendEmail({
to: Session.getActiveUser().getEmail(),
subject: 'Test Email markup2 - ' + new Date(),
htmlBody: htmlBody,
});
} // end if minute test
}// end if hour test
}// end if day test
}// end if month test
}// end for loop
}
Can you try:
<html>
<head>
<script>
(function() {
var detail2 = document.getElementById("detail2").innerHTML;
document.getElementById("detail2_val").innerHTML = detail2;
})();
</script>
</head>
<body>
<p>
<br>"Punctual?" <span id="detail2_val"></span><br>
</p>
</body>
</html>
Currently, this line:
var htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();
will not evaluate a template.
The method being used is:
createHtmlOutputFromFile('mail_template')
HtmlService has quite a few methods for creating html content. You need to use:
HtmlService.createTemplateFromFile(filename).evaluate()
There are some possible things that could go wrong in your overall work flow. If the situation is one in which you are writing data, and then immediately trying to read that same data that was just written, there could be a problem with the new data not being available to be read in such a short time span.
I would use:
SpreadsheetApp.flush();
immediately after writing the new data, and before creating the template.
Only your third html example has code for a template. To retrieve data and put it into a template, a scriptlet must either run a function, that then retrieves the data, or the data must be in global variables. The situation with global variable makes no sense, because you are using dynamic data, so a function would need to run to first put the data into a global variable. The function might as well just return the data directly. So, your scriptlet will probably need to run a server side function and return text or HTML to the html template. You probably need to use a printing scriptlet.
Apps Script documentation - force printing scriptlets
The website is supposed to display a message counting down to the tax day. I can't seem to get anything to display on the page. The scrollbar doesn't even show up with the color even though I put in the write code. Some advice please.
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<title>TaxDay</title>
<script type="text/javascript">
<!-- Hide from old browsers
function scrollColor() {
styleObject=document.getElementsByTagName('html')[0].style
styleObject.scrollbarFaceColor="#857040"
styleObject.scrollbarTrackColor="#f4efe9"
}
function countDown() {
var today = new Date()
var day of week = today.toLocaleString()
dayLocate = dayofweek.indexOf(" ")
weekDay = dayofweek.substring(0, dayLocate)
newDay = dayofweek.substring(dayLocate)
dateLocate = newday.indexOf(",")
monthDate = newDay.substring(0, dateLocate+1)}
yearLocate = dayofweek.indexOf("2016")
year = dayofweek.substr(yearLocate, 4)
var taxDate = new Date ("April 16, 2017")
var daysToGo = taxDate.getTime()-today.getTime()
var daysToTaxDate = Math.ceil(daysToGo/(1000*60*60*24))
function taxmessage() {
var lastModDate = document.lastModified
var lastModDate = lastModDate.substring(0,10)
taxDay.innerHTML = "<p style='font-size:12pt; font-
family:helvetica;'>Today is "+weekDay+" "+monthDate+" "+year+".
You have "+daysToTaxDate+" days to file your taxes.</p>"
}
}
//-->
</script>
The <div> id is taxDay if it's relevant. The body onLoad event handlers are scrollColor(); countDown(); and taxmessage().
you are not closing the countdown() function before the taxmessage() function - meaning that taxmessage is nested within countdown(). Also you do not have semicolons ";" after each line of the js. You should rewrite the code to either include the function of taxmessage() or close out countdown() first and call taxmessage with arguments passed to get the date variables.
check your console for errors
I am new to web development.
Today I learn about classes(function) in javascript. I got an error how to call dynamically added method.
My Code :
<head runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
MyMethod("start", function () { return "hi"; });
var abc = this.start(); //gives error
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<div>
<input type="button" value="Click" onclick="MyFunction1()"/>
</div>
</form>
Here when I click the input button then not able to call the dynamically added function
How can i call the start() function that i added here.
Please Help me.
Thanks in Advance.
this in MyFunction1 referes to the global object in that case(for browsers it is window) , because you call MyFunction1 as function and you don't create an object by using new MyFunction1().
Another thing to be noted. You should not use eval when it is possible to do it without eval.
You can do the same thing using:
function MyMethod(name, fn) {
MyFunction1.prototype[name] = fn;
}
Using eval prevents you from using optimization tools or tools to validate your code. At least most of these tools don't take eval into account or even give a warning about that you are using it.
Try adding "new" before your onclick call to MyFunction1, creating an instance of it.
It reseolved I did
Hi , It resolved .Thanks for the gret help i did :
function fnOnload() {
MyMethod("start", function () { return "hi"; });
}
function MyMethod(name, fn) {
var str = "MyFunction1.prototype." + name + "= fn;";
eval(str);
}
function MyFunction1() {
}
function MyFunction2()
{
var aa = new MyFunction1();
var answee = aa.start();
}
and in click of button i callled function MyFunction2()
without changing your code you can do as follow , but I say it would be helpful if you read about invocations types and about this variable.
function MyMethod(name, fn) {
MyFunction1.prototype[name]= fn;
return MyFunction1.prototype;
}
function MyFunction1() {
var myPrototype= MyMethod("start", function () { return "hi"; });
var returnValue = myPrototype.start();
console.log(returnValue);
}
I'm attempting to make a simple linear text game that will display inside a div on a webpage. I am using innerHTML to write the contents of the game to the div, and using onclick from a button to change the contents. My problem is that I would also like to include a few user-submitted variables, which I am trying to do using prompt() inside a function.
The problem is, I can't get the variable to set globally. It works when called inside the function, but nowhere else.
I've tried declaring the variable first outside the function, using window.variable (both inside and outside of the function) as well as leaving off the var before the variable inside the function to make it global in scope.
I have looked for solutions and nothing seems to work! Am I missing something with the order of my script?
Here is the javascript:
var cb2 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next3,\'continueBttn\',cb3);">';
var cb3 = '<input id="button" type="button" value="Continue" onclick="getName();">';
var cb4 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next5,\'continueBttn\',cb5);">';
var cb5 = '<input id="button" type="button" value="Continue" onclick="replace(\'gamebox\',next6,\'continueBttn\',cb6);">';
var testName = "Test Name";
var player1;
var next2 = "<p>Great, you've certainly got an adventurer's spirit! Now I just need a few details about you and your party.</p>";
var next3 = "<p>First, I'd like to get everyone's name</p>"
var next4 = "<p>Thanks " + testName + "!</p>"
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
var continueButton = function (content) {
document.getElementById('continueBttn').innerHTML = content;
};
function replace(id1,content,id2,cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
function getName() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox',next4,'continueBttn',cb4);
}
And here is the html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="oregon.css" />
</head>
<body>
<div id="gameContainer">
<div id="gamebox">
<p>Welcome to the Oregon Trail! Click Continue to travel the trail!</p>
</div>
</div>
<div id="continueBttn"><input id="button" type="button" value="Continue" onclick="replace('gamebox',next2,'continueBttn',cb2);"></div>
</body>
</html>
<script src="oregon.js" type="text/javascript"></script>
Ok, I got your stuff to work. Take the var off of the variables to make them global and change your functions to be assigned to a variable like continueButton:
replace = function(id1, content, id2, cb) {
document.getElementById(id1).innerHTML = content;
document.getElementById(id2).innerHTML = cb;
}
getName = function() {
player1 = prompt("What is your Name?");
alert("Your name is " + player1 + ".");
replace('gamebox', next4, 'continueBttn', cb4);
}
This got things working for me.
The other answers here have good points as well, you need a better way of handling the player name.
player1 is used into the expression next5, not next4 (which is the one of your getName() function)
Anyway, it will never work like this. At the moment next5 is initialized the value of player1 was defined a certain way, and will remain defined that way unless you redefine the next5 variable again.
You need to encapsulate the next5 definition into a function in order to make it dynamic.
Problem is here
var next5 = "<p>Now you're ready " + player1 + "! Click to set out on the trail!</p>"
It uses the variable when it is first rendered, it will not be updated when you set player1 to a new value.
You need to figure out a different way to set the player's name. One way of doing it is to replace it.
var next5 = "<p>Now you're ready {player1}! Click to set out on the trail!</p>"
and when you use it
var newStr = next5.replace("{player1}", player1);