How do I display an unordered list in JavaScript? - javascript

I have to display a text field and a button “Generate times table”. When the user enters an integer from 1 to 9 and clicks the button, two duplicate times tables will appear side-by-side. However, the times tables on the right needs to be presented in an unordered list style.
When the user enters another number and click the button, the old times tables disappear and the new times tables will be generated accordingly.
I have managed to display one times tables set, however the second version (unordered list) won't display adjacent to it.
<html>
<head>
</head>
<body>
Enter integer:<input onClick="stopCounterAnimation()" id="number"
type="text">
<button onclick="startCounterAnimation()">Start Animation</button>
<button onclick="stopCounterAnimation()">Stop Animation</button>
<br/><br/>
<span id="counter"></span>
<script>
var counter = 0;
var counterSchedule;
var input = document.getElementById("number");
var counterSpan = document.getElementById("counter");
function startCounterAnimation() {
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter() {
if (~~input.value) {
if (counter >= 9)
counter = 0;
counter++;
counterSpan.innerHTML = input.value + " X " + counter + " = "
+ eval(input.value + " * " + counter);
}
}
function stopCounterAnimation() {
clearInterval(counterSchedule);
input.value = "";
counter = 0;
}
</script>
</body>
</html>

Related

How to Append Increments in a Function Individually to a List?

My issue is I am not sure how to type the code to increment trainADistance by trainAMPM and decrease trainBDistance by trainBMPM in the do loop while having each text appended to the list. Each minute is supposed to be appended individually with text += "Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2);. An example is listed below. Any help would be appreciated.
What the function is supposed to do?
The function I have been attempting to create is supposed to allow the user to input three variables trainAMPH, trainBMPH and distanceApart. When the inputs are submitted, the function function calculateTrains() is supposed to calculate trainAMPH, trainBMPH into miles per minute trainAMPM and trainBMPM. There is a do-while loop in place to increment the minutesi , increment trainADistance by trainAMPM and decrease trainBDistance by trainBMPM. trainBDistance is supposed to contain the same value as distanceApart. The loop continues while(trainADistance < trainBDistance) and is supposed to append text into a list until the loop is broken. An example is listed below.
This is an example of what is supposed to be appended to to the list with inputs 70 for train A, 60 for train B and 260 for distance
• Minute 1 Train A Position: 1.17 miles Train B Position: 259.00 miles
• Minute 2 Train A Position: 2.33 miles Train B Position: 258.00 miles
• Minute 3 Train A Position: 3.50 miles Train B Position: 257.00 miles
• Minute 4 Train A Position: 4.67 miles Train B Position: 256.00 miles
• Minute 5 Train A Position: 5.83 miles Train B Position: 255.00 miles
My Code
<script>
function calculateTrains(){
let trainAMPH= document.getElementById("trainAMPH").value;
let trainBMPH= document.getElementById("trainBMPH").value;
let distanceApart = trainBDistance = document.getElementById("distanceApart").value;
let list = document.getElementById("list");
//calculates MPH into MPM(miles per minute)
trainAMPM = (trainAMPH / 60);
trainBMPM = (trainBMPH / 60);
let trainADistance = 0;
let text = "";
let i = 0;
let li = "";
// do that increments the minutes and Train A/Train B's current position
d do{
text += "Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2);
i++;
trainADistance += parseFloat(trainAMPM);
trainBDistance -= parseFloat(trainBMPM);
li = document.createElement("li");
}
// while loop tht continues while Train A distance is less than Train B distance
while(trainADistance < trainBDistance)
//adds "text" variable listed in do while loop to list
li.innerHTML = text;
list.appendChild(li);
// documents the amount of minutes to the "results" div
document.getElementById("results").innerHTML = "The two trains met after " + i + "minutes.";
}
</script>
<body>
<form id="myForm">
<label>Train A's Speed</label>
<input id="trainAMPH" type="number" value="" placeholder="MPH">
<label>Train B's Speed</label>
<input id="trainBMPH" type="number" value="" placeholder="MPH" >
<label>Distance between Eastford and Westford</label>
<input id="distanceApart" type="number" value=""placeholder="Miles">
<input type ="button" value="Submit Values" onclick="calculateTrains()">
<ul id = "list"></ul>
<div id="results"></div>
</form>
</body>
There were some issue with the code, I have made the necessary changes. Please go through the in-line comments that I have added in order to understand what were the mistakes and how they can be fixed.
The code is working now, please use the below snippet to run and see it's output. Do make sure to see my comments. Goodluck!
function calculateTrains() {
let trainAMPH = +document.getElementById("trainAMPH").value;
let trainBMPH = +document.getElementById("trainBMPH").value;
let distanceApart, trainBDistance;
//The input you retrieve using .value will be a string, convert it to Number using + to use toFixed
distanceApart = trainBDistance = +document.getElementById("distanceApart")
.value;
let list = document.getElementById("list");
//calculates MPH into MPM(miles per minute)
trainAMPM = trainAMPH / 60;
trainBMPM = trainBMPH / 60;
let trainADistance = 0;
let i = 1;
let text = "";
// do that increments the minutes and Train A/Train B's current position
do {
//don't use text+=, you don't want to append, you want each <li> to be on a separate line
text =
"Minute " +
i +
" Train A Position: " +
trainADistance.toFixed(2) +
" miles" +
"Train B Position: " +
trainBDistance.toFixed(2);
//create list item using template literals
let li = `<li>${text}</li>`;
//use insertAdjaventHTML( ) function to append the above created literal to list <ul>
list.insertAdjacentHTML("beforeend", li);
//increment i
i++;
//do the train A and train B distance calculations
//without these calculations, your while exit condition from below will never be met,
//making it an infinite while loop
trainADistance += trainAMPM;
trainBDistance -= trainBMPM;
} while (
// while loop tht continues while Train A distance is less than Train B distance
trainADistance < trainBDistance
);
//don't use innerHTML to append text, innerHTML is to append HTML string like '<div> hello <div>'
//instead use textContent or innerText properties
document.getElementById("results").textContent =
"The two trains met after " + i + "minutes.";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<body>
<form id="myForm">
<label>Train A's Speed</label>
<input id="trainAMPH" type="number" value="" placeholder="MPH" />
<label>Train B's Speed</label>
<input id="trainBMPH" type="number" value="" placeholder="MPH" />
<label>Distance between Eastford and Westford</label>
<input id="distanceApart" type="number" value="" placeholder="Miles" />
<input
type="button"
value="Submit Values"
onclick="calculateTrains()"
/>
<ul id="list"></ul>
<div id="results"></div>
</form>
</body>
<script src="script.js"></script>
</body>
</html>
the reason why trainBDistance.toFixed(2) isn't recognized as a function is because when call document.getElementById("distanceApart").value the data type is string u need to parseInt or parseFloat that value first. You condition is while(trainADistance < trainBDistance) so you need to increment trainADistance as you said.
This might help.
function calculateTrains(){
let trainAMPH= document.getElementById("trainAMPH").value;
let trainBMPH= document.getElementById("trainBMPH").value;
let distanceApart = trainBDistance = parseInt( document.getElementById("distanceApart").value );
let list = document.getElementById("list");
list.innerHTML = ''; //empty the list
//calculates MPH into MPM(miles per minute)
trainAMPM = (trainAMPH / 60);
trainBMPM = (trainBMPH / 60);
let trainADistance = 0;
let i = 0;
// do that increments the minutes and Train A/Train B's current position
do{
let text = "Minute " + i + " Train A Position: "+ trainADistance.toFixed(2) + " miles" + " Train B Position: " + trainBDistance.toFixed(2);
//adds "text" variable listed in do while loop to list
let li = document.createElement("li");
li.innerHTML = text;
list.appendChild(li);
i++;
trainADistance += trainAMPM; //increment trainADistance by trainAMPM
trainBDistance -= trainBMPM; //decrease trainBDistance by trainBMPM
}while(trainADistance < trainBDistance)
// while loop tht continues while Train A distance is less than Train B distance
// documents the amount of minutes to the "results" div
document.getElementById("results").innerHTML = "The two trains met after " + i + "minutes.";
}
You may wanna change you script to as follows:
<script>
function calculateTrains(){
let trainAMPH= document.getElementById("trainAMPH").value;
let trainBMPH= document.getElementById("trainBMPH").value;
let distanceApart = trainBDistance = document.getElementById("distanceApart").value;
let list = document.getElementById("list");
trainAMPM = (trainAMPH / 60);
trainBMPM = (trainBMPH / 60);
let trainADistance = 0;
let text = "";
let i = 0;
do{
i++;
trainADistance+=trainAMPM
trainBDistance-=trainBMPM
let li = document.createElement('li')
li.textContent="Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2)
document.getElementById('list').appendChild(li)
}while(trainADistance<=trainBDistance)
}
</script>

How to update and save the variable after it has been changed?

I want to update the value of the counting variable after the words have been clicked, so they can be sorted from the highest clicked value from an array.
The variable value doesn't carry over to the next button.
I made the two variables as global variables in order to use it in other functions, but it doesn't seem to work and I also want the submit button to get updates after the user clicks the words after they have submitted once.
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed=0 ;
var countArbitrated=0;
var mostChosen = [
{word:"addressed:", selectedTimes:countAddressed},
{word:"arbitrated:", selectedTimes:countArbitrated}];
//set every buttons for action words
function addressed() {
countAddressed += 1;
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
//count how many individual action words there are.
document.getElementById("demo1").innerHTML ="arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen.sort(function(a, b){return b.selectedTimes - a. selectedTimes});
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
----I want this :
Communication
addressed(button) , arbitrated (button),
addressed: 3
arbitrated: 5
Sort(button)
addressed: 5
arbitrated: 3
----but I am getting this:
Communication
addressed , arbitrated ,
addressed: 3
arbitrated: 5
Sort
addressed: 0
arbitrated: 0
As I have mentioned in the comment, you are not updating mostChosen array when buttons are clicked.
// Update addressed count in addressed() function
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
// Similar update is done in arbitrated() function
Here is the running code (your code, modified slightly) that modifies the array mostChosen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Prescriptions</title>
</head>
<body>
<h4> Communication </h4>
<button onclick="addressed()">addressed</button> ,
<button onclick="arbitrated()">arbitrated</button> ,
<br>-------------------
<p id="demo"> </p>
<p id="demo1"> </p>
<button onclick="myFunction()">Sort</button>
<p id="demo3"></p>
<script>
var countAddressed = 0;
var countArbitrated = 0;
var mostChosen = [
{ word: "addressed:", selectedTimes: countAddressed },
{ word: "arbitrated:", selectedTimes: countArbitrated }];
//set every buttons for action words
function addressed() {
countAddressed += 1;
mostChosen.forEach(token => {
if (token.word == 'addressed:') {
token.selectedTimes = countAddressed;
}
});
//count how many individual action words there are.
document.getElementById("demo").innerHTML = "addressed: " + countAddressed;
}
function arbitrated() {
countArbitrated += 1;
mostChosen.forEach(token => {
if (token.word == 'arbitrated:') {
token.selectedTimes = countArbitrated;
}
});
//count how many individual action words there are.
document.getElementById("demo1").innerHTML = "arbitrated: " + countArbitrated;
}
function myFunction() {
mostChosen = mostChosen.sort(function (a, b) { return b.selectedTimes - a.selectedTimes });
displayWords();
}
function displayWords() {
document.getElementById("demo3").innerHTML =
mostChosen[0].word + " " + mostChosen[0].selectedTimes + "<br>" + mostChosen[1].word + " " + mostChosen[1].selectedTimes + "<br>";
}
</script>
</body>

How to find frequency of numbers in a list from user input HTML

I'm trying to make a code that will give the sum, average, min, max, and frequency of numbers in a list. With the help of others, I was able to get the sum, average, max, and min, but not frequency. Im trying to make it so that when you click on a button that is next to the other math function buttons, it alerts you with how many times all of the numbers have shown up in the list. For example, if the list of numbers the user types in is 1,7,7,7,3,1, and the user clicks on the frequency button it outputs how many times 1 is in the list (2), how many times 7 is in the list (3), and how many times 3 is in the list (1).
.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button id="sum"> Sum </button>
<button id="max"> Max </button>
<button id="min"> Min </button>
<button id="avg"> Avg </button>
<div>
<button value="Refresh Page" onclick="window.location.reload()" > Reset! </button>
</div>
<script>
let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
// This will add the input number to the list and clear the input
function addClick () {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
update();
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable(){
if(this.value === ""){
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This will calculate and update all variable values
function update() {
sum = 0;
min = Infinity;
max = -Infinity;
var count = 0;
for (var i of list.children) {
let val = +i.textContent;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
count++;
}
avg = sum/count;
}
// This functions will alert the numbers
function sumClick() {
alert("The sum of your numbers is: " + sum);
}
function avgClick() {
alert("The average of your numbers is: " + avg);
}
function minClick() {
alert("The smaller number is: " + min);
}
function maxClick() {
alert("The greater number is: " + max);
}
// Here we add all events
input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
</script>
</body>
</html>
An alternative is keeping the frequency/counter in an object where the keys are the entered numbers.
let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = -Infinity;
var max = Infinity;
let frequency = Object.create(null);
// This will add the input number to the list and clear the input
function addClick() {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
update(input.value);
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable() {
if (this.value === "") {
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This will calculate and update all variable values
function update(enteredValue) {
frequency[enteredValue] = (frequency[enteredValue] || 0) + 1;
sum = 0;
min = Infinity;
max = -Infinity;
var count = 0;
for (var i of list.children) {
let val = +i.textContent;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
count++;
}
avg = sum / count;
}
function frequencyClick() {
let text = Object.entries(frequency).reduce((a, [number, fqy]) => {
return a.concat(`The number ${number} appeared ${fqy} time(s) in the list`)
}, []).join('\n');
alert(text);
}
// This functions will alert the numbers
function sumClick() {
alert("The sum of your numbers is: " + sum);
}
function avgClick() {
alert("The average of your numbers is: " + avg);
}
function minClick() {
alert("The smaller number is: " + min);
}
function maxClick() {
alert("The greater number is: " + max);
}
// Here we add all events
input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
document.getElementById("frequency").addEventListener("click", frequencyClick);
.title {
font-weight: bold;
margin-top: 1em;
}
<link rel="stylesheet" type="text/css" href="style.css">
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button id="sum"> Sum </button>
<button id="max"> Max </button>
<button id="min"> Min </button>
<button id="avg"> Avg </button>
<button id="frequency"> Frequency </button>
<div>
<button value="Refresh Page" onclick="window.location.reload()"> Reset! </button>
</div>
One way is to create a map that you update with the frequency of each number then output the results.
function calcFreq() {
return list.children.map(i => +i.textContent).reduce((acc, val) => {
if (acc[val]) {
acc[val] += 1;
} else {
acc[val] = 1;
}
return acc;
}, {});
}

Google Apps Script - Email stock notification?

Hi there!
I am a beginner both in JavaScript and in Google Sheets, but I am trying to find a way for Google Apps Script to basically scan the data I have brought in there from a Swedish Online Bank where they have some information about how the stocks go up and down.
Furthermore, I want to be notified by email when one of these on my list goes down by for example 5 % in a day.
I tried something like this:
let arrayRow = ["+" + 5.91 + "%", "+" + 5.22 + "%", "-" + 5.5 + "%"];
console.log(arrayRow);
function stockPricePlus() {
if (arrayRow >= "+" + 5 + "%") {
console.log("Yay! One of your stocks are going up by 5 % or more!");
}
}
function stockPriceMinus() {
if (arrayRow <= "-" + 5 + "%") {
console.log("Oh noes! One of your stocks are going down by 5 % or more!");
}
}
stockPricePlus();
stockPriceMinus();
And this works in my JavaScript file, but I am not quite sure how to make it pull the data continuously from the Google Sheets and run through them like a loop?
I found something on the internet that seemed to kind of do the job, but I also see that there are some missing parts in the code.
function sendEmails () {
var sheet = SpreadsheetApp.getActiveSheet();
var Price = sheet.getRange("B34:B").getValues();
var data = Price.getValues();
var results = [];
for (var i = 0; i < data.length; ++i) {
var row = data[i];
Logger.log(Price);
if (Price >= "+" + 5 + "%") {
MailApp.sendEmail("johnsmith#gmail.com", "Stock Price Alert from Stock Price Google Script", "One of your stocks are going up by 5 % or more!");
}
if (Price <= "-" + 5 + "%") {
MailApp.sendEmail("johnsmith#gmail.com", "Stock Price Alert from Stock Price Google Script", "One of your stocks are going down by 5 % or more!");
}
A ClientSide Timer for Collecting Periodic Stock Prices using GoogleFinance cell formulas
This code is a portion of code that I have used to check stocks. It has a timer function which runs clientside on your browser and you can adjust the sampling rate as you desire. I'd recommend no less that once every 5 minutes. That gives a good long time to get everything done. I also added a checkStats function which calculates percent change using the formula (max-min/max) * 100 and it compares this value with a value that you can set for each stock on the StockPrices page. It is also set up to send emails if the percent change is greater than a threshold and you can set. You can have as many stocks as you wish but you may need to adjust the sample rate if you try to get too many. You will have to add the email recipient address.
I have several other functions which chart the various stocks in different ways that I didn't include in this. I tried to keep this simple so I wouldn't be surprised if I have inadvently left some things out. Please note this script does not start automatically each day. In fact I hardly ever use it but I thought it would be an interesting thing to do and since then I've found the timer portion to be quite handy.
It's been my experience that GoogleFinance tags do not refresh regularly throughout the day. I've seen them not change at all for as long as 12 minutes while watching the stock prices change on another more elaborate system that runs on a personal computer.
datatimer.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<style>
#my_block{border:2px solid black;background-color:rgba(0,150,255,0.2);padding:10px 10px 10px 10px;}
#conv_block{border: 1px solid black;padding:10px 10px 10px 10px;}
.bttn_block{padding:5px 5px 0px 0px;}
.sndr_block {border:1px solid rgba(0,150,0,0.5);background-color:rgba(150,150,0,0.2);margin-bottom:2px;}
</style>
</head>
<body>
<form>
<div id="my_block" class="block form-group">
<div class="sndr_block">
<div id="myClock" style="font-size:20px;font-weight:bold;"></div>
<br />Timer Duration(minutes):
<br /><input id="txt1" type="text" size="4" class="action"/>
<select id="sel1" onChange="loadTxt('sel1','txt1');">
</select>
<div id="cntdiv"></div>
<br /><strong>Timer Controls</strong>
<div class="bttn_block"><input type="button" value="Start" name="startShow" id="startShow" onClick="startmytimer();changeData();" class="red" /></div>
<div class="bttn_block"><input type="button" value="Stop" name="stopTimer" id="stopTimer" class="red" /></div>
<div class="bttn_block"><input type="button" value="Single Ping" name="changedata" id="chgData" class="red" onClick="changeData();" /></div>
</div>
<div id="btn-bar">
<br /><input type="button" value="Exit" onClick="google.script.host.close();" class="green" />
</div>
</div>
</form>
<script>
var idx=1;
var myInterval='';
var cnt=0;
$(function() {
var select = document.getElementById('sel1');
select.options.length = 0;
for(var i=1;i<61;i++)
{
select.options[i-1] = new Option(i,i * 60000);
}
select.selectedIndex=4;
$('#startTimer').click(startmytimer);
$('#stopTimer').click(stopTimer);
$('#txt1').val(String(select.options[select.selectedIndex].value));
startTime();
});
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('myClock').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i){
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
function startmytimer(){
document.getElementById('cntdiv').innerHTML='<strong>Timer Started:</strong> ' + document.getElementById('myClock').innerHTML;
myInterval=setInterval(changeData, Number($('#txt1').val()));
}
function stopTimer(){
document.getElementById('cntdiv').innerHTML='Timer Stopped';
clearInterval(myInterval);
}
function loadTxt(from,to){
document.getElementById(to).value = document.getElementById(from).value;
}
function changeData(){
$('#txt1').css('background','#ffffcc');
google.script.run
.withSuccessHandler(updateDisplay)
.changeData();
}
function updateDisplay(t){
$('#txt1').css('background','#ffffff');
document.getElementById('cntdiv').innerHTML='<strong>Timer Running:</strong> Count= ' + ++cnt + ' <strong>Time:</strong> ' + t;
}
console.log('My Code');
</script>
</body>
</html>
Code.gs:
function onOpen(){
SpreadsheetApp.getUi().createMenu('MyTools')
.addItem('Show Timer SideBar', 'showTimerSideBar')
.addToUi();
}
//This is the function driven by the clientside timer trigger It also creates new data sheets for each day.
function changeData(){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('StockPrices');
var rg=sh.getRange(3,1,1,sh.getLastColumn());
var vA=rg.getValues();
var n=new Date();
var tmr=Utilities.formatDate(n, Session.getScriptTimeZone(), "HH:mm:ss");
var ts=Utilities.formatDate(n, Session.getScriptTimeZone(), "E-MMddyy-HHmmss");
var sheetTitle=Utilities.formatDate(n, Session.getScriptTimeZone(), "E-MMddyy");
vA[0][0]=ts;
if(isSheet(sheetTitle)){
ss.getSheetByName(sheetTitle).appendRow(vA[0]);
}else{
var sht=ss.insertSheet(sheetTitle);
var hA=sh.getRange(1,1,1,sh.getLastColumn()).getValues();
hA[0][0]="TimeStamp";
sht.appendRow(hA[0]);
sht.appendRow(vA[0]);
}
checkStats(sheetTitle);
return tmr;
}
function showTimerSideBar()
{
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('StockPrices');
sh.getRange(5,2,1,sh.getLastColumn()-1).clearContent();//clears the sent row
var ui=HtmlService.createHtmlOutputFromFile('datatimer').setTitle('Javascript Trigger Generator');
SpreadsheetApp.getUi().showSidebar(ui);
}
function isSheet(sheetname){
var r=false;
var ss=SpreadsheetApp.getActive();
var allSheets=ss.getSheets();
for(var i=0;i<allSheets.length;i++){
if(allSheets[i].getName()==sheetname){
r=true;
break;
}
}
return r;
}
//This function checks stats and compares them to limits to determine if warning email messages should be sent
function checkStats(page) {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(page);
var rg=sh.getRange(1,2,sh.getLastRow(),sh.getLastColumn()-1);
var vA=rg.getValues();
var minA=vA[1].slice(0);
var maxA=vA[1].slice(0);
var pchA=[];
for(var i=2;i<vA.length;i++) {
for(var j=0;j<vA[i].length;j++) {
if(vA[i][j]>maxA[j]) {
maxA[j]=vA[i][j];
}
if(vA[i][j]<minA[j]) {
minA[j]=vA[i][j];
}
}
}
for(var i=0;i<minA.length;i++) {
pchA.push(Number(((maxA[i]-minA[i])/maxA[i]) * 100).toFixed(2));
}
var spsh=ss.getSheetByName('StockPrices');
var limitA=spsh.getRange(4,2,1,spsh.getLastColumn()-1).getValues();
var nameA=spsh.getRange(1,2,1,spsh.getLastColumn()-1).getValues();
var sentA=spsh.getRange(5,2,1,spsh.getLastColumn()-1).getValues();
var msgA=[];
for(var i=0;i<pchA.length;i++) {
if(pchA[i]>limitA[i] && sentA[i]!="SENT") {
msgA.push({name:nameA[i],change:pchA[i],limit:limitA[i],index:i});
}
}
if(msgA.length>0){
var html="<h1>Stocks Exceeding Change Limit</h1>";
var text='Stocks Exceeding Change Limit\n';
for(var i=0;i<msgA.length;i++) {
html+=Utilities.formatString('<br />Stock Name: <strong>%s</strong><br />Limit: <strong>%s</strong><br />Change: <strong>%s</strong><hr width="100%"/><br />', msgA[i].name,msgA[i].limit,msgA[i].change);
text+=Utilities.formatString('\nStock Name: %s\nLimit: %s\nChange: %s\n\n', msgA[i].name,msgA[i].limit,msgA[i].change);
sentA[msgA[i].index]="SENT";
}
//GmailApp.sendEmail(recipient, 'Stocks Exceeding Change Limit', text, {htmlBody:html})
spsh.getRange(5,2,1,spsh.getLastColumn()-1).setValues(sentA);
}
}
This is what the Stock Prices page looks like:
This is what a daily data page looks like:
And this is what the timer sidebar looks like:
Apps Script Documentation

I want to calculate 2 input fields and display (print) it to the <p> tag

Hi friends (Gurus) I would be very glad if someone helps me out. Thank you great people. You always help. Any further tips or explanation would be appreciated.
<script>
function cal() {
var firstNumber = document.getElementById("first").value;
var secondNumber = document.getElementById("second").value;
var total = firstNumber + secondNumber;
document.getElementById("display").innerHTML=total;
}
function ca4l2() {
var firstNumber = document.getElementById("first").value;
var secondNumber = document.getElementById("second").value;
var total = firstNumber + secondNumber;
document.getElementById("display").innerHTML=total;
}
</script>
<input type="number" id="first" onKeyPress="cal()"> +
<input type="number" id="second" onKeyPress="cal2()">
<p id="display"></p
Try this.
DEMO
HTML:
<input type="number" id="first"> +
<input type="number" id="second">
<button id="btn">
Calculate
</button>
<p id="display"></p>
JavaScript:
var first = document.getElementById('first'),
second = document.getElementById('second'),
btn = document.getElementById('btn'),
display = document.getElementById('display');
btn.addEventListener(
"click", CalNum, false);
function CalNum() {
display.innerHTML = parseInt(first.value) + parseInt(second.value);
}
As requested from OP, this is another example of how to calculate
numbers without using a button to fire the function.
HTML:
<input type="number" id="first"> +
<input type="number" id="second">
<p id="display"></p>
CSS
#display {
animation: OpacityBlink 1s linear infinite;
/*You need to use -webkit- and all other properties for this transition to work on all browsers.*/
}
#keyframes OpacityBlink {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
JavaScript
var first = document.getElementById('first'),
second = document.getElementById('second'),
display = document.getElementById('display');
first.addEventListener(
"keyup", CalNum, false); //assigns the keyup event listener
second.addEventListener(
"keyup", CalNum, false); //assigns the keyup event listener
function CalNum() {
if (first.value === "" || second.value === "") {
display.innerHTML = "Calculating.."; //if inputs value is empty display this string
} else {
display.style.animation = "none"; // stops the css3 animation
display.innerHTML = parseInt(first.value) + parseInt(second.value); //displays the final result
}
}
/* Please note that this only work if the user uses his keyboard to type the numbers. The CalNum function only fires if the event detects keyup, otherwise nothing will happen. You can always add another event listener for mouse clicks as well. */
Change to this,
var total = parseInt(firstNumber) + parseInt(secondNumber);
if the number is decimal, then,
var total = parseFloat(firstNumber) + parseFloat(secondNumber);

Categories