Javascripts calculates total based on form selections - javascript

I have an html form that I want to use javascript to calculate the total based on values of the form selection.
I was able to get my code work, but after trying to save it to JS fiddle it doesn't seem to be calculating anymore. Is there something in my code that is causing the error?
Here is the link to my full code:
https://jsfiddle.net/kmurray13/gc02Lsmh/
Here is just my javascript:
function calculatePrice(){
//Get selected data
var elt = document.getElementById("Quantity");
var quantity = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("size");
var size = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("page_count");
var page_count = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("cover_stock");
var cover_stock = elt.options[elt.selectedIndex].value;
var elt = document.getElementById("text_stock");
var text_stock = elt.options[elt.selectedIndex].value;
//convert data to integers or decimals
quantity = parseInt(quantity);
size = parseFloat(size);
page_count = parseInt(page_count);
cover_stock = parseFloat(cover_stock);
text_stock = parseFloat(text_stock);
//calculate total value
var total = ((cover_stock * quantity)) + ((text_stock * page_count) * quantity);
//print value to PicExtPrice
document.getElementById("PicExtPrice").value=total;
}
My goal is to get the calculation when you click the 'Calculate Price' button, but I am not sure what I have done to the code to cause this error.

No it's not anything in your code that's causing the issue. It's because you were loading the javascript in the onload event thus the calculatePrice function wasn't present in the DOM thus you were getting the error. Fixed here: https://jsfiddle.net/fm3g64x0/

This is because jsFiddle is configured by default to wrap your JS code in onload event handler. If you look in your console you are getting a ReferenceError for calculatePrice() because it is out of scope.
In the Javascript jsFiddle pane, click where it says JavaScript + No-Library (pure JS) and where it says Load Type select No wrap - bottom of and rerun your code.

Related

Javascript - localStorage issues

In the script below, I want to be able to display on the main html page lists of paragraphs saved in the localstorage. In the html I defined an are with the id "content". I want to display the texte stored in the localstorage in this area.
In the script below the function "displaylocalstorage" does not allow me to display the values that have been saved in the localstorage with the function "storedparagraphs". Can you please give me some guidelines to correct the "displaylocalstorage" function? Is my while loop correct ? Is the way I call the fucntion "display locastorage" is correct ?
Here is the html and js script below:
Javascript:
const mybutton = document.getElementById ("addbutton");
const mytext = document.getElementById("mytext");
const content = document.getElementById("content");
function displaylocalstorage() {
let n = 0;
while (localStorage.getItem("content" + n)) {
n++;
}
while (n){
const paragraph = document.createElement("p");
paragraph.innerText = localStorage.getItem("content");
content.appendChild(paragraph);
n++
}
}
}
displaylocalstorage()
displaylocalstorage is not being called.
add this to your js
const buttonshow = document.getElementById("buttonshow");
buttonshow.addEventListener("click", displaylocalstorage);
and to your html:
<input
type="button"
value="show"
id="buttonshow"
class="buttonshowall"
/>
and console log items in the displaylocalstorage
Thank would be a good start. Other than this in that paragraph remove length from n as n is a number. If you keep it as length it will error.
if(n>0){
let lastposition = n -1;
localStorage.removeItem("content", lastposition)
}
Another big one is change const n to let as you try to update n and const won't allow you to do that.

google-apps-script cannot read array value ("typeError: "cannot read property "1" ) [duplicate]

This question already has an answer here:
Freezing rows in Sheets with Google Apps throws type error
(1 answer)
Closed 2 years ago.
I'm trying to make my code sending an email by referring to my google sheet data. Im using Apps Script and here is the code. However, as I run my function "sendEmail()", I got "typeError: "cannot read property "1" of undefined(line 17)".
Code line 17
var currentEmail = rows[i][1];
Here is the full code.
var ss = "1kuTkOuCd-wKTS2564oHdxALFbFo-IeyjzToYYhB6NrQ";
var SheetName = "FormResp";
function getRows(){
var rangeName = 'FormResp!A2:E';
var rows = Sheets.Spreadsheets.Values.get(ss, rangeName).values;
return rows;
}
function sendEmails() {
var ss_1 = SpreadsheetApp.openById(ss);
var sheet = ss_1.getSheetByName(SheetName);
var lr = sheet.getLastRow();
for (var i = 0;i<=lr;i++){
rows=getRows();
var currentEmail = rows[i][1];
var startingdate = rows[i][3];
var endingdate = rows[i][4];
MailApp.sendEmail(currentEmail,"Thank You for Applying Leave via Leave form: your request leave starting" + startingdate + "until" + endingdate,"Hello");
}
}
function testgetrow(){
var nama = getRows();
var x = "";
}
I do make a test function "testgetrow()" to check my data, and I do manage to run the function without any error and I do confirm that there is values in my getRows() function.
my getRows() function working, and there is a value in the array as shown in the picture below.
I suppose you can do it any way you wish but this seems a lot simpler to me.
function sendEmails() {
const ss = SpreadsheetApp.openById("1kuTkOuCd-wKTS2564oHdxALFbFo-IeyjzToYYhB6NrQ");
const sh = ss.getSheetByName('FormResp');
const rg = sh.getRange(2,1,sh.getLastRow()-1,5);
const vs=rg.getValues();
vs.forEach(r=>{
var currentEmail = r[1];
var startingdate = r[3];
var endingdate = r[4];
MailApp.sendEmail(currentEmail,"Thank You for Applying Leave via Leave form: your request leave starting" + startingdate + "until" + endingdate,"Hello");
});
}
Answer
The main problem is that you have not declared properly the variable rows in your line 16 rows=getRows(); because you forgot to use the keyword var. Change that line with var rows = getRows() and try it again.
Take a look
You are mixing SpreadsheetApp with Sheets API. I recommend you to pick one and stay there to have a clear and less confusing code.
Try use less functions if they are not really necessary, as #Cooper suggested, you can define the variable rows with getRange that can handle A1 notation ranges and getValues.
Define properly your range in A1 notation: if you write A2:E, your range goes from column A, row 2 until column E, row 1000. You have to add the number of the last row in your range, for example A2:E10.
With the last change, you do not have to calculate the last row, you can simply use rows.length.
It is not necessary to have the id of the spreadsheet if your script is a Container-bound Scripts and not a Standalone Script with getActiveSpreadsheet
I attach you a snippet of the code:
var sheetName = "FormResp";
var spreadsheet_id = "1kuTkOuCd-wKTS2564oHdxALFbFo-IeyjzToYYhB6NrQ";
var ss = SpreadsheetApp.openById(spreadsheet_id).getSheetByName(sheetName)
function sendEmails() {
var rangeName = 'A1:B9';
var rows = ss.getRange(rangeName).getValues()
for (var i = 0; i <= rows.length; i++){
var currentEmail = rows[i][1];
var startingdate = rows[i][3];
var endingdate = rows[i][4];
MailApp.sendEmail(currentEmail,"Thank You for Applying Leave via Leave form: your request leave starting" + startingdate + "until" + endingdate,"Hello");
}
}
I hope that it helps you!
References
SpreadsheetApp
Sheets API
getRange
getValues
getActiveSpreadsheet
Container-bound Scripts
Standalone Script

How can i create a sum and display it from a Database value?

I am using a Firebase db. I have a value i display on my page that increments and updates itself which can be seen on the web page.
I also have predetermined total value.
I want to create a sum that has the total value be decreased by the previously mentioned dynamic value. and send an alert to the user on the web page when it hits 0.
However I can't seem to get this to work, this is what I tried:
// here I create the sum for the total amount
var total = 0;
function getData(){
for (var i = 0; i < HoeveelheidArr.length; i++) { //my arrawy from user input which i extracted
total += parseInt(HoeveelheidArr[i]);
}
}
//here i push the values to my DB
function writeData(){
firebase.database().ref("Exercise").set({
totalReps: total,
totalRepsLeft: progressLeft,
});
//Here I update the DYNAMIC value on my page it gets incremented by 1 by my arduino on an event. this works
var progressList = document.getElementById("progressList");
var wemosRep = function(element, value){
element.textContent = value;
}
//get value from db and auto pass update if change in value
var startWemosRep = firebase.database().ref('Reps/Value');
startWemosRep.on('value', function(snapshot){
wemosRep(progressList,snapshot.val());
});
//now the part that doesnt work... Just like before I try to first create the sum and then display it on my page if this value changed.
progressLeft = parseInt( startWemosRep) - total ; //this doesnt!
var pageProgressLeft = document.getElementById("progressLeft");
var repLeft = function (element, value){
element.textContent = value;
};
var startTotalRep = firebase.database().ref('Exercise/progressLeft');
startTotalRep.on('value', function(snapshot){
repLeft(pageProgressLeft, snapshot.val());
});
}
// I get the total value i pushed in my DB named totalGet!
function gotData(data){
firebase.database().ref('Exercise').once('value').then (function(snapshot){
var totalGet = snapshot.val().totalReps;
document.getElementById("totalList").innerHTML=totalGet;
})
The progressLeft variable doesn't get returned, that is what it boils down to. It doesn't display on my page nor do I know if it works. I tried everything at this point I cant see the end of the tunnel. Hope you can help me out with this.

How can get last value of form charge in jQuery

I am trying to make a form where a customer can choose parson and automatically show the cost depend on parson number. So for that, I used jQuery form change function and calculate the cost inside of the function. My all logic is working ok but the issue is when increasing number then showing multiple costs.
Visual look:
Always I want to show the last one/ updated one
Blow my code:
var adultsSingleChage = 200;
var childrenSingleCharge = 100;
var infantsSingleCharge = 50;
$('#absbt_form input').change(function(){
var adults = $("#absbt_adults").val();
var adultsCharge = adults * adultsSingleChage;
var children = $("#absbt_children").val();
var childrenCharge = children * childrenSingleCharge;
var infants = $("#absbt_infants").val();
var infantsCharge = infants * infantsSingleCharge;
var totalCharge = adultsCharge + childrenCharge + infantsCharge;
console.log(totalCharge);
$('.total_cost').append(totalCharge);
});
I know I did the maximum of logic but for last logic, I'm confused.
How can I just show the last one?
append adds new content to existing one - that's the reason of having previous values.
Instead of using append use text:
$('.total_cost').text(totalCharge);
The problem is with the code you are appending which means you are adding the text into the element instead of replacing it. You can use the following two methods:
text(): $('.total_cost').text("iota")
html(): $('.total_cost').html("iota")
Note: Use id selector or with class use $($('.total_cost')[0])
Use html(totalCharge) instead of append(totalCharge)

My JS is not running, shows POST error

I am writing an online loan calculator for practice. The data processing is all done on the client-side, however, JSFiddle wants me to use POST. Why is this? Could this be related to the fact that when the calculate button is clicked locally, the form just clears? The code in a JSFiddle: http://jsfiddle.net/TJonS/CuzSM/
Also, why isn't this calculating on click of the button? I have tried debugging multiple times, but Chrome is showing no errors.
Javascript:
function calculate(){
//get the elements
var amount = document.getElementById("amount");
var rate = document.getElementById("rate");
var duration = document.getElementById("duration");
//get the values of the elements
var a = parseFloat(amount.value);
var r = parseFloat(rate.value);
var d = parseFloat(duration.value);
//grab the outputable (readable(ha ha:))) variables
var principal = a;
var interest = r/100/12;
var time = d *12;
//now the calculation variables
var x = Math.pow(1+interest, payments);
var monthlypay = (principal*x*interest)/(x-1);
//if the result is a finite number, then display it. Else we're messed up!
if (isFinite(monthlypay)) {
//fill in outputs
payment.innerHTML = monthlypay.toFixed(2);
total.innerHTML = (monthlypay * payments).toFixed(2);
totalinterest.innerHTML = ((monthlypay*payments)-principal).toFixed(2);
//save the variables
save(amount.value, rate.value,duration.value, a.value, r.value, d.value, principal.value, total.value, totalinterest.value)
}
//else just make the outputs blank as can be.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
}
just put
return false;
at the bottom of your calculate function, to stop the default onClick behavior(of the button) performing a form post.
also...
is your if statement "if (isFinite(monthlypay)) {" actually getting focus?
this seems to be wiping the values every time.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
check your "isFinite(monthlypay)" function is returning true. (most probably never)
Button without post on click:
<input type="button" onclick="dosomething();" value="my button text" />

Categories

Resources