qureySelector not finding className [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 days ago.
My code for class keeps giving me
SCRIPT.JS:24 Uncaught TypeError: Cannot set properties of null (setting 'className')
at SCRIPT.JS:24:47
Here is my Java Script so far
//Seting some variables to make coding easier
let userGreet = document.querySelector("#userGreet");
let userData = document.querySelector("#userData");
let userName = prompt("What is your name?");
alert("Hello "+userName+", Lets Calculate your purchase");
//Here we prompt the user for the price of there 2 items
let item1 = parseFloat(prompt("How Much it your first Item?"));
let item2 = parseFloat(prompt("How much is your second item?"));
//Now we add those items together to get the total
let total = item1 + item2;
//Now we will use if & elseif statements to see if the user gets a discount on their purchase
if (_total => 100){
let afterDiscount = total * .10;
document.querySelector("body").className = "discount";
userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
userData.innerHTML = "Your purchase total is $" + afterDiscount + ", which includes your 10% discount.";
} else if (_total => 50){
let afterDiscount = total * .05;
document.querySelector("body").className = "discount";
userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
userData.innerHTML = "Your purchase total is $" + afterDiscount + ", which includes your 5% discount.";
} else if (total < 50){
document.querySelector("body").className = "nonDiscount";
userGreet.innerHTML = "Hello " + userName + ", Here is your Total.";
userData.innerHTML = "Your purchase total is $" + total;
}
Here is my HTML so far
<!DOCTYPE html>
<html>
<head>
<title>CE05 QuertSelector</title>
<script src="JS/SCRIPT.JS"></script>
</head>
<body class="body">
<link rel="stylesheet" href="CSS/STYLE.CSS">
<h1 id="topOf">QuerySelector</h1>
<h3 id="userGreet">Hello User</h3>
<p id="userData">let play with QuerySelector</p>
</body>
</html>
and finaly here is my CSS
body {
background-color: rgb(255, 255, 255);
}
h1 {
color: rgb(1, 1, 1);
}
h3{
Color: rgb(0, 0, 0);
}
p {
font-family: verdana;
font-size: 20px;
}
.discount{
background-color: rgb(25, 225, 25) ;
}
.nonDiscount{
background-color: rgb(216, 239, 12);
}
I feel like I'm missing something obvious, help with this would be apreciated.
The code should change the background collor depending on the total cost of the 2 items, then change the h3 and p1 text to tell the user their total.

Your script tag is running before the elements are created. You can fix this by moving it to the end of the body.
<!DOCTYPE html>
<html>
<head>
<title>CE05 QuertSelector</title>
</head>
<body class="body">
<link rel="stylesheet" href="CSS/STYLE.CSS">
<h1 id="topOf">QuerySelector</h1>
<h3 id="userGreet">Hello User</h3>
<p id="userData">let play with QuerySelector</p>
<script src="JS/SCRIPT.JS"></script>
</body>
</html>

Related

I am stuck in getting the HTML button to begin the JS script

After my last question, I tried to use the JS file and it wouldn't work alongside clicking an HTML button to begin the functions in the JS file; After the JS script asks for money and the code for a soda product, I couldn't restart the function again from clicking "BEGIN" in my HTML page.
How do I solve this?
*I would like to challenge myself to script Javascript functions without using the function in HTML.
*I am using AUD denominations since I live in Australia.
var beginMachine = document.getElementById("beginMachine");
beginMachine.addEventListener("click", vendingFunction);
function vendingFunction() {
var $money = 0;
var codeSequence = ["A1", "A2", "B1", "B2"];
var $soda = ["Coca-Cola", "Fanta", "Sprite", "Schweppes"];
const coinValue = {'0.20': 0.20, '0.50': 0.50, '1.00': 1.00, '2.00': 2.00};
const sodaPrice = [1.55, 2.95, 1.85, 3.90];
const formatMoney = new Intl.NumberFormat('en-AU', {style: 'currency', currency: 'AUD'}).format; //Change the currency format to AUD for clarity in currency used.
return {
insertCoin: () => { //The arrow function '=>' acts a simple indicator to call a function
var coin = window.prompt("Insert any coin. (20c, 50c, $1, $2)");
$money += coinValue[coin] || 0;
if (typeof coinValue[coin] === 'undefined') alert('Invalid Choice'); //'undefined' means no value or invalid value
console.log('You now have ' + formatMoney($money));
},
selectItem: () => {
var sodaChoice = window.prompt("Select your code.");
console.log(sodaChoice);
if (sodaChoice == "A1") {
window.alert("You selected Coca-Cola.");
window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
window.alert(sodaPrice[0] <= $money ? "You have enough." : "You don't have enough.");
}
if (sodaChoice == "A2") {
window.alert("You selected Fanta.");
window.alert("This costs $" + sodaPrice[1] + ".");
window.alert(sodaPrice[1] <= $money ? "You have enough." : "You don't have enough.");
}
if (sodaChoice == "B1") {
window.alert("You selected Sprite.");
window.alert("This costs $" + sodaPrice[2] + ".");
window.alert(sodaPrice[2] <= $money ? "You have enough." : "You don't have enough.");
}
if (sodaChoice == "B2") {
window.alert("You selected Schweppes");
window.alert("This costs $" + sodaPrice[3] + ".");
window.alert(sodaPrice[3] <= $money ? "You have enough." : "You don't have enough.");
}
}
}
}
const app = vendingFunction();
for (let i = 0; i < 5; i++) {
app.insertCoin();
}
app.selectItem();
//Code from dave in StackOverflow <https://stackoverflow.com/questions/67929579/how-do-you-program-this-javascript-file-for-allowing-more-than-one-denominations/67929809
//See <https://www.youtube.com/watch?v=qsEtXR38IQ8&ab_channel=EnvatoTuts%2B>
body {background-color: lightgrey;}
.vendingMachine
{
position:static;
top: 0;
left: 0;
z-index: 1;
}
.mainFont
{
font-family: Arial, sans-serif;
font: 12px/14px;
}
<!DOCTYPE html>
<html> <!-- Tells this document is coded in HTML5 -->
<head>
<link rel="stylesheet" href="0az_style.css"><!-- Links to the CSS file that handles the layout and design of the webiste, specifically the buttons' and vending machine's positions. -->
<title>Vending Machine</title> <!-- Names the browser tab -->
</head>
<!--Calls the mainFont variable in the CSS file to change every letter into Arial-->
<body class="mainFont"><!--Changes every letter to a specific font-->
<!--Creates a large heading like Heading 1 in Word-->
<h1>Welcome to the Vending Machine</h1>
<!--<div> generically stores CSS code but for these lines, Javascript is called upon to activate the remaining scripts-->
<div>
<img class="fit-picture"
src="Vending-Machine-alt.png"
width="1255"
height="1835"
alt="Picture of a vending machine.">
</div>
<br>
<!-- From https://stackoverflow.com/questions/9530954/how-to-call-external-javascript-function-in-html -->
<!-- Adding <script type="text/javascript"></script> calls this function right away. Perhaps use inline JS to tell the button to load JS script after the page loads.-->
<button id="beginMachine">BEGIN</button>
<br>
<!--<a href= '0az_how_to_use.html'> links to the manual page in this project's main folder-->
<h2><a href= '0az_how_to_use.html'>How to use the vending machine</a></h2>
</body>
</html>
Your vendingFunction() function returns an object with functions, it doesn't execute them. You need another function that would execute them:
var beginMachine = document.getElementById("beginMachine");
beginMachine.addEventListener("click", start);
function vendingFunction() {
var $money = 0;
var codeSequence = ["A1", "A2", "B1", "B2"];
var $soda = ["Coca-Cola", "Fanta", "Sprite", "Schweppes"];
const coinValue = {'0.20': 0.20, '0.50': 0.50, '1.00': 1.00, '2.00': 2.00};
const sodaPrice = [1.55, 2.95, 1.85, 3.90];
const formatMoney = new Intl.NumberFormat('en-AU', {style: 'currency', currency: 'AUD'}).format; //Change the currency format to AUD for clarity in currency used.
return {
insertCoin: () => { //The arrow function '=>' acts a simple indicator to call a function
var coin = window.prompt("Insert any coin. (20c, 50c, $1, $2)");
$money += coinValue[coin] || 0;
if (typeof coinValue[coin] === 'undefined') alert('Invalid Choice'); //'undefined' means no value or invalid value
console.log('You now have ' + formatMoney($money));
},
selectItem: () => {
var sodaChoice = window.prompt("Select your code.");
console.log(sodaChoice);
if (sodaChoice == "A1") {
window.alert("You selected Coca-Cola.");
window.alert("This costs $" + sodaPrice[0] + "."); //sodaprice[0] calls the first element in "sodaPrice's" array
window.alert(sodaPrice[0] <= $money ? "You have enough." : "You don't have enough.");
}
if (sodaChoice == "A2") {
window.alert("You selected Fanta.");
window.alert("This costs $" + sodaPrice[1] + ".");
window.alert(sodaPrice[1] <= $money ? "You have enough." : "You don't have enough.");
}
if (sodaChoice == "B1") {
window.alert("You selected Sprite.");
window.alert("This costs $" + sodaPrice[2] + ".");
window.alert(sodaPrice[2] <= $money ? "You have enough." : "You don't have enough.");
}
if (sodaChoice == "B2") {
window.alert("You selected Schweppes");
window.alert("This costs $" + sodaPrice[3] + ".");
window.alert(sodaPrice[3] <= $money ? "You have enough." : "You don't have enough.");
}
}
}
}
function start()
{
const app = vendingFunction();
for (let i = 0; i < 5; i++) {
app.insertCoin();
}
app.selectItem();
}
start();
//Code from dave in StackOverflow <https://stackoverflow.com/questions/67929579/how-do-you-program-this-javascript-file-for-allowing-more-than-one-denominations/67929809
//See <https://www.youtube.com/watch?v=qsEtXR38IQ8&ab_channel=EnvatoTuts%2B>
body {background-color: lightgrey;}
.vendingMachine
{
position:static;
top: 0;
left: 0;
z-index: 1;
}
.mainFont
{
font-family: Arial, sans-serif;
font: 12px/14px;
}
<!DOCTYPE html>
<html> <!-- Tells this document is coded in HTML5 -->
<head>
<link rel="stylesheet" href="0az_style.css"><!-- Links to the CSS file that handles the layout and design of the webiste, specifically the buttons' and vending machine's positions. -->
<title>Vending Machine</title> <!-- Names the browser tab -->
</head>
<!--Calls the mainFont variable in the CSS file to change every letter into Arial-->
<body class="mainFont"><!--Changes every letter to a specific font-->
<!--Creates a large heading like Heading 1 in Word-->
<h1>Welcome to the Vending Machine</h1>
<!--<div> generically stores CSS code but for these lines, Javascript is called upon to activate the remaining scripts-->
<div>
<img class="fit-picture"
src="Vending-Machine-alt.png"
width="1255"
height="1835"
alt="Picture of a vending machine.">
</div>
<br>
<!-- From https://stackoverflow.com/questions/9530954/how-to-call-external-javascript-function-in-html -->
<!-- Adding <script type="text/javascript"></script> calls this function right away. Perhaps use inline JS to tell the button to load JS script after the page loads.-->
<button id="beginMachine">BEGIN</button>
<br>
<!--<a href= '0az_how_to_use.html'> links to the manual page in this project's main folder-->
<h2><a href= '0az_how_to_use.html'>How to use the vending machine</a></h2>
</body>
</html>

How to create a JavaScript loop to display an output 100 times

I’m doing an exercise for high school. The exercise is to create an input and the input needs to be displayed 100 times ( 1) input 2) input 3) input, etc..) and you are not allowed to do it manually; you need to create a loop.
This is what I have so far. I tried googling it for an hour, but I didn't find anything.
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script>
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var textFromUser = getText("myTextField");
var str = something;
showReply("output", reply);
}
var something = [
[var text = "";]
[var i;]
[for (i = 0; i < 5; i++) {]
[reply += i + ")" + textFromUser;}]
]
</script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output"></span> </p>
</body>
</html>
How can I do it?
You can create an element and append to your output container using a for loop. Try this:
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
let container = document.getElementById(id);
let p = document.createElement('p');
p.textContent = reply;
container.appendChild(p);
}
function reply(){
var textFromUser = getText("myTextField");
for(let i = 0; i < 100; i++){
showReply("output", textFromUser);
}
}
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <div id="output"></div> </p>
Variable i is used as a counter. If you want to change how many times it loops, just change the i<=num.
for (var i=1; i<=100; i++){
show_reply();
}
I suggest you to check this post on W3Schools.
I've made two files, one for HTML and the other for JavaScript.
Here is the JavaScript code:
function getText(id) {
let text = document.getElementById(id).value;
return text;
}
function showReply(id, reply) {
document.getElementById(id).innerHTML = reply;
}
function reply() {
let textFromUser = getText("myTextField");
let i;
let span1 = document.getElementById("output")
let usert = ""
for (i = 0; i < 100; i++) {
usert += "<br>" + textFromUser
}
span1.innerHTML = usert
}
Here is the HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script src="main.js"></script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output">dd</span> </p>
</body>
</html>
There are many different potential solutions for this type of question. Choose the flavor you like and put your own spin on it.
function showReply(id, reply){
document.getElementById(id).innerHTML = reply.join('<br>');
}
function reply(){
var textFromUser = getText('myTextField');
var outputs = [];
for (let i = 0; i < 100; i++){
outputs.push(`#${ i } ${ textFromUser }`)
}
showReply('output', outputs);
}

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

There's a simple logic error in my JS that I lack the knowledge to find

<!DOCTYPE html>
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice = document.getElementById("partPrice").value;
var totalPrice;
function calcTotal() {
if (partPrice <= 25) {
var totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
var totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
So my goal is to show interest + $1.50 for a total cost below or equal to $25 and 10% interest of a total cost above $25. My problem is that the "partPrice", which is the price that the user enters, is not being received. I've looked up quite a bit about this and I've seen people go around by creating multiple variables to pick up certain values but I have yet to understand why. I would really like an explanation because, going through this code, it all looks logically correct. I'm really lost as to where I should be changing my syntax.
Update your code to following
Move the get value code inside the function
Convert the value which is a string to a number
function calcTotal() {
var partPrice = parseFloat(document.getElementById("partPrice").value);
...
}
Just get data inside function. also remove variable declaration in if statement
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice,
totalPrice;
function calcTotal() {
partPrice = document.getElementById("partPrice").value;
if (partPrice <= 25) {
totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
var partPrice = document.getElementById("partPrice").value;
This line is executed once when the script is loaded, so partPrice will be an empty string. It doesn't get reevaluated automatically when you write anything in input, so you'll have to call document.getElementById("partPrice").value again in calcTotal to fetch the current value of partPrice.

Add values of javascript array

I'm trying to complete a system with which a book shop can enter the a sample of 5 books that were sold that day along with their prices. These values would then be displayed to the page.
I have managed this and now wish to add the total price. I have tried all the methods mentioned on stack overflow and elsewhere to get the sume of the price array but I either get the last price entered or "NaN" when i try to get the total. Please help!!!
Here is my code
document.addEventListener("DOMContentLoaded", function() {
enterBooks()
}); // Event listener - When page loads, call enterBooks function
function enterBooks() { // enterBooks function
var books = []; // Defines books variable as an array
for (var i = 0; i < 5; i++) { // for loop to loop 5 times
books.push("<li>" + prompt("Enter a book") + "</li>"); // PUSH adds a new item to the array in the form of a prompt with <li> tags either side of each.
var price = []; // Defines price variable as an array
for (var p = 0; p < 1; p++) { // for loop to loop 1 time
price.push("<li>" + "£" + parseInt(prompt("Enter the price")) + "</li>"); // Once again PUSH adds a new item to the array in the form of a prompt with <li> tags either side of each. This then displays next to each book.
}
document.getElementById("displayPrice").innerHTML += (price.join(""));
document.getElementById("displayBooks").innerHTML = (books.join(""));
}
// --------- This is the part i cannot seem to get -----------
var total = 0;
for (var t = 0; t < price.length; t++) {
total = total + price[t];
}
document.getElementById("total").innerHTML = total;
}
ul {
list-style-type: decimal; /* Gives list items numbers */
font-size:25px;
width:20%;
}
#displayBooks {
float:left;
width:20%;
}
#displayPrice {
float:left;
width:50%;
list-style-type: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Bookshop</title>
<link href="css/style.css" rel="stylesheet">
<!-- StyleSheet -->
</head>
<body class="text-center">
<h1>BookShop</h1>
<!-- Header -->
<h3>Books sold</h3>
<!-- Team intro -->
<ul id="displayBooks">
<!-- Div to display the teams -->
</ul>
<ul id="displayPrice">
<!-- Div to display the teams -->
</ul>
<div id="total">
</div>
<script src="js/script.js"></script>
</body>
</html>
P.S This is my first time asking a question on here so if it's not structured very well then I apologise in advance and hope you can still make it all out
try this:
document.addEventListener("DOMContentLoaded", function() {
enterBooks()
}); // Event listener - When page loads, call enterBooks function
function enterBooks() { // enterBooks function
var books = []; // Defines books variable as an array
var price = [];
var priceText=[];
for (var i = 0; i < 5; i++) { // for loop to loop 5 times
books.push("<li>" + prompt("Enter a book") + "</li>"); // PUSH adds a new item to the array in the form of a prompt with <li> tags either side of each.
price[i]=parseInt(prompt("Enter the price"));
priceText.push("<li>" + "£" + price[i] + "</li>"); // Once again PUSH adds a new item to the array in the form of a prompt with <li> tags either side of each. This then displays next to each book.
document.getElementById("displayPrice").innerHTML = priceText.join("");
document.getElementById("displayBooks").innerHTML = (books.join(""));
}
// --------- This is the part i cannot seem to get -----------
var total = 0;
for (var t = 0; t < price.length; t++) {
total = total + price[t];
}
document.getElementById("total").innerHTML = total+ "£";
}
ul {
list-style-type: decimal; /* Gives list items numbers */
font-size:25px;
width:20%;
}
#displayBooks {
float:left;
width:20%;
}
#displayPrice {
float:left;
width:50%;
list-style-type: none;
}
<!DOCTYPE html>
<html>
<head>
<title>Bookshop</title>
<link href="css/style.css" rel="stylesheet">
<!-- StyleSheet -->
</head>
<body class="text-center">
<h1>BookShop</h1>
<!-- Header -->
<h3>Books sold</h3>
<!-- Team intro -->
<ul id="displayBooks">
<!-- Div to display the teams -->
</ul>
<ul id="displayPrice">
<!-- Div to display the teams -->
</ul>
<div id="total">
</div>
<script src="js/script.js"></script>
</body>
</html>
It is because you are adding the entire HTML in the price array and hence it will not add as it is not numerical data.
This should work:
var input = parseInt(prompt("Enter the price"));
price.push(input);
please change
for (var p = 0; p < 1; p++) { // for loop to loop 1 time
price.push("<li>" + "£" + parseInt(prompt("Enter the price")) + "</li>"); // Once again PUSH adds a new item to the array in the form of a prompt with <li> tags either side of each. This then displays next to each book.
}
document.getElementById("displayPrice").innerHTML += (price.join(""));
to
// no need for loop
price.push(parseInt(prompt("Enter the price"), 10)); // just the price, added base to parseInt (really? not parseFloat?)
document.getElementById("displayPrice").innerHTML += price.map(function (a) {
return '<li>GBP' + a + '</li>'; // build here the string for output
}).join("");

Categories