how can I correct this JavaScript adding function? - javascript

I have a form which takes six inputs (there are more but only these matter for now)
original fare
original tax
new fare
new tax
fee
number of guests
when "Calculate" is pressed I use javascript to add original fare
and original tax to get the original total
then I add new fare and new tax to get the new total
now I compare original total to new total
if original total is greater than new total it should use one if several methods to finish doing the math I need and set the results to the display
i was originally testing everything using these values:
original fare = 1000
original tax = 200
new fare = 800
new tax = 200
fee = 150
number of guests = 3
which can bee seen here https://pnrbuilder.com/_popups/exchangeMyPNR_MATH_TEST_2.php
(page only works in chrome)
the above works exactly as expected but when I change the values to:
original fare = 949.83
original tax = 321.18
new fare = 453.91
new tax = 143.91
fee = 150
number of guests = 3
seen here https://pnrbuilder.com/_popups/exchangeMyPNR_MATH_TEST.php
(page only works in chrome)
this test uses the wrong if statement to finish out the rest of the math
I dont understand why this is happening as original total is still > new total so it should use the same method as the first example. I put in alerts to let me know exactly which if statement is being used to do the math and clearly the wrong one is used here but I just cant figure out why.
I know this is convoluted but could someone please help me figure out where my logic goes wrong?
Here's the full function:
function addMe(frm) {
var orBase = Number(frm.box1.value);
var orTax = Number(frm.box2.value);
var nwBase = Number(frm.box3.value);
var nwTax = Number(frm.box4.value);
var fee = Number(frm.fee.value);
var gsts = Number(frm.guests.value);
var fltrd_orBase = orBase * 100;
var fltrd_orTax = orTax * 100;
var fltrd_orTtl = fltrd_orBase + fltrd_orTax;
var orTtl = fltrd_orTtl / 100;
var final_orTtl = orTtl.toFixed(2)
frm.result.value = orTtl.toFixed(2)
var fltrd_nwBase = nwBase * 100;
var fltrd_nwTax = nwTax * 100;
var fltrd_nwTtl = fltrd_nwBase + fltrd_nwTax;
var nwTtl = fltrd_nwTtl / 100;
var final_nwTtl = nwTtl.toFixed(2)
frm.result2.value = nwTtl.toFixed(2)
var e = document.getElementById("residual");
var selectVal = e.options[e.selectedIndex].value;
if (final_orTtl <= final_nwTtl) {
document.getElementById("forfeitTable").style.display="none";
document.getElementById("MCOtable").style.display="none";
var undiff = final_nwTtl - final_orTtl;
var diff =undiff
document.getElementById("differenceDisplay").innerHTML=diff.toFixed(2);
frm.difference.value = diff.toFixed(2);
var ppCost = diff + fee;
frm.pptotal.value = ppCost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=ppCost.toFixed(2);
var ttlCost = ppCost * gsts;
frm.totalcost.value = ttlCost.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlCost.toFixed(2);
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 1 was used');
}
}
else if (final_orTtl > final_nwTtl) {
if (selectVal == "residualX" || selectVal == "residualN") {
document.getElementById("MCOtable").style.display="none";
var diff = final_orTtl - final_nwTtl;
var displayDiff = diff* -1;
document.getElementById("differenceDisplay").innerHTML= displayDiff.toFixed(2);
frm.difference.value = displayDiff.toFixed(2);
document.getElementById("forfeitInfo").innerHTML = "Beyond the cost above";
frm.lost.value = diff.toFixed(2);
document.getElementById("ppForfeitedDisplay").innerHTML = diff.toFixed(2);
var ttlfForfeited = diff * gsts;
frm.lostTTL.value = ttlfForfeited.toFixed(2);
document.getElementById("totalForfeitedDisplay").innerHTML=ttlfForfeited.toFixed(2);
var ppCost = fee;
frm.pptotal.value = ppCost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=ppCost;
var ttlCost = fee * gsts;
frm.totalcost.value = ttlCost.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlCost;
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
document.getElementById("forfeitTable").style.display="table";
}
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.1 was used');
}
}
// this is the method that should be used below
else if (selectVal == "residualA" ) {
document.getElementById("MCOtable").style.display="none";
var diff = final_orTtl - final_nwTtl;
var displayDiff = diff* -1;
document.getElementById("differenceDisplay").innerHTML= displayDiff.toFixed(2);
frm.difference.value = diff.toFixed(2);
if ( diff > fee) {
var residual = diff - fee ;
document.getElementById("forfeitInfo").innerHTML = "No additional cost. However,";
frm.lost.value = residual.toFixed(2);
document.getElementById("ppForfeitedDisplay").innerHTML = residual.toFixed(2);
var ttlfForfeited = residual * gsts;
frm.lostTTL.value = ttlfForfeited.toFixed(2);
document.getElementById("totalForfeitedDisplay").innerHTML=ttlfForfeited.toFixed(2);
//document.getElementById("differenceDisplay").innerHTML=0;
frm.difference.value = diff;
document.getElementById("ppDisplay").innerHTML=0;
document.getElementById("grandTotalDisplay").innerHTML=0;
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
document.getElementById("forfeitTable").style.display="table";
}
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.2 was used');
}
}
else {
var remBal = fee - diff ;
var ttlcost = remBal * gsts;
frm.totalcost.value = ttlcost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=remBal.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlcost.toFixed(2);
document.getElementById("forfeitTable").style.display="none";
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.3 was used');
}
}
}
else if (selectVal == "residualM" ) {
var diff = final_orTtl - final_nwTtl;
var displayDiff = diff* -1;
document.getElementById("differenceDisplay").innerHTML= displayDiff.toFixed(2);
frm.difference.value = displayDiff.toFixed(2);
if (diff > fee) {
var mco = diff - fee ;
document.getElementById("MCOInfo").innerHTML=mco.toFixed(2);
frm.MCOamt.value = mco.toFixed(2);
//document.getElementById("differenceDisplay").innerHTML=diff;
//frm.difference.value = diff* -1;
frm.totalcost.value = 0;
document.getElementById("ppDisplay").innerHTML=0;
document.getElementById("grandTotalDisplay").innerHTML=0;
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
document.getElementById("forfeitTable").style.display="none";
document.getElementById("MCOtable").style.display="table";
}
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.4 was used');
}
}
else {
var remBal = fee - diff ;
var ttlcost = remBal * gsts;
frm.totalcost.value = ttlcost.toFixed(2);
document.getElementById("ppDisplay").innerHTML=remBal.toFixed(2);
document.getElementById("grandTotalDisplay").innerHTML=ttlcost.toFixed(2);
document.getElementById("forfeitTable").style.display="none";
document.getElementById("MCOtable").style.display="none";
// this is just for testing to show which method was actually used
if (orBase != "" && orTax != "" && nwBase != "" && nwTax != "" && fee != "" && gsts != "") {
// this is in its own if statement so it doesnt popuop while entering data
alert('if 2.5 was used');
}
}
}
}

var nwTtl = fltrd_nwTtl / 100;
var final_orTtl = orTtl.toFixed(2)
var orTtl = fltrd_orTtl / 100;
var final_orTtl = orTtl.toFixed(2)
if (final_orTtl > final_nwTtl ) {
}
This part seems to be my problem. the if comparison im doing here doesnt seem to like the '.toFixed(2)' that I did above it for some reason. I changed it to:
var nwTtl = fltrd_nwTtl / 100;
var orTtl = fltrd_orTtl / 100;
if (orTtl > nwTtl ) {
}
Im still testing all the other features but this seems to be working as expected so far. I would still love to know why my use of '.toFixed(2)' causes two numbers that are clearly higher vs lower to evaluate to the opposite. and will accept any answer to that part of this question

Related

Calculation with javascript

I have a script that completes a calculation for each row of my table and then add the rows together. The calculation is alway correct if it consists of the first row only. For some reason, I'm getting an incorrect calculation when the other rows are included in the calculation.
var total = 0;
var a1 = Number(this.getField("o1i").value);
var a2 = Number(this.getField("o1iother").value);
var b1 = Number(this.getField("o2i").value);
var b2 = Number(this.getField("o2iother").value);
var c1 = Number(this.getField("o3i").value);
var c2 = Number(this.getField("o3iother").value);
var d1 = Number(this.getField("o4i").value);
var d2 = Number(this.getField("o4iother").value);
var e1 = Number(this.getField("o5i").value);
var e2 = Number(this.getField("o5iother").value);
var t = Number(this.getField("time").value);
for(var i=1; i<=15; i++){
if(this.getField("ins."+i).valueAsString == "o1" &&
this.getField("mins"+i).valueAsString != "")
total += t*a1+a2;
else if(this.getField("ins."+i).valueAsString == "o2" &&
this.getField("mins"+i).valueAsString != "")
total += t*b1+b2;
else if(this.getField("ins."+i).valueAsString == "o3" &&
this.getField("mins"+i).valueAsString != "")
total += t*c1+c2;
else if(this.getField("ins."+i).valueAsString == "o4" &&
this.getField("mins"+i).valueAsString != "")
total += t*d1+d2;
else if(this.getField("ins."+i).valueAsString == "o5" &&
this.getField("mins"+i).valueAsString != "")
total += t*e1+e2;}
if(total == 0)event.value = 0;
else
event.value = total;

How to get modified column in this app script function

I had a function working qute well but I can not modify something. I need this cell to add new values once I select a new option in the drop down. This only for the 9th and 11th columns, but is not working well.
function onEdit(e){
addValue(e);
}
function addValue(e) {
// Vairables
var ws = "HR Support";
var identifiedBy = 9;
var impDimension = 11;
// Get modified column
var col = e.range.getColumn();
if( col === identifiedBy || col === impDimension || e.oldValue == null || e.value == null
&& e.source.getActiveSheet().getName() === ws) return;
e.range.setValue(e.oldValue+", "+e.value);
}
I probably need a little more information but this does something close what I think you're looking for. Let me know what else you need.
function onEdit(e) {
//e.source.toast('entry');
const sh = e.range.getSheet();
if (sh.getName() == "HR Support" && (e.range.columnStart == 9 || e.range.columnStart == 11) && e.range.rowStart > 2) {
//e.source.toast('cond');
e.range.setValue(e.oldValue + ", " + e.value);
}
}
I think maybe you want this:
function onEdit(e) {
e.source.toast('entry');
const sh = e.range.getSheet();
sh.getRange('A1').setValue(JSON.stringify(e));
if (sh.getName() == "HR Support" && (e.range.columnStart == 9 || e.range.columnStart == 11) && e.range.rowStart > 2) {
e.source.toast('cond');
if (!e.hasOwnProperty('oldValue')) {//checks to see if oldValue is a property of event object
e.range.setValue(e.value);
} else {
e.range.setValue(e.oldValue + ", " + e.value);
}
}
}

if statements being skipped even when both expressions are true

I have a webpage that populates a table with arrays. It has a doClick function so that when a user clicks on a cell it passes the row and column of the cell to the function. Example cell: onclick="doClick(0,1)"
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if ((top != -1) && (cells[top][col].innerHTML = ""))
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && (cells[row][right].innerHTML = ""))
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML = ""))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((left != -1) && (cells[row][left].inn = ""))
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
. The problem is, even if both if expressions are true, the if statement is being skipped and it's falling through to the else statement. I've desk checked it and run it through the developer tools and checked values. A statement that was true on both expressions was skipped. Any suggestions?
cells[row][right].innerHTML = ""
is wrong. You are missing the double (triple) =.
The correct way should be...
cells[row][right].innerHTML === ""
It looks like maybe there are a few typos or misconceptions in your code.
A quick note about Conditions in an IF statement
A statement like (cells[top][col].innerHTML = "") as a condition will always return true as this is setting cells[top][col].innerHTML as "" or at least instantiating the variable. So, the proper condition to test absolutely true or false would be (cells[top][col].innerHTML === ""). However, you can get away with not even doing that and simply replace (cells[top][col].innerHTML = "") with cells[top][col].innerHTML. You may run into some other issues though is the variable is not instantiated already, either way. I would wrap the latter logic in an IF statement to check if cells[top][col].innerHTML is even instantiated.
To fix this, check out the following modifications I have made to your code.
function doClick(row, col)
{
var top = row -1;
var bottom = row +1;
var left = col -1;
var right = col +1;
var swapped = false;
if(typeof cells[top][col].innerHTML !== 'undefined' $$ cells[top][col].innerHTML !== null)
{
if ((top != -1) && cells[top][col].innerHTML !== '')
{
cells[top][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((right != 4) && cells[row][right].innerHTML !== '')
{
cells[row][right].innerHTML = cells[row][col].innerHTML ;
cells[row][col].innerHTML = "";
swapped = true;
}
else if ((bottom != 4) && (cells[bottom][col].innerHTML))
{
cells[bottom][col].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
else if (typeof cells[row][left].inn !== 'undefined' && (left != -1) && cells[row][left].inn !== '')
{
cells[row][lef].innerHTML = cells[row][col].innerHTML;
cells[row][col].innerHTML = "";
swapped = true;
}
else
{
alert("Illegal Move.");
}
}
An example working to demonstrate the above code
var testVar1 = '';
var testVar2 = 'Hello';
// var testVar3; <- Left this un-instantiated to test existance
// Testing if a var is empty but exists
if(typeof testVar1 !== 'undefined' && testVar1 !== null){
if(testVar1 !== ''){
alert('testVar1 has a value!');
}{
alert('testVar1 does not have a value!');
}
}
// Testing if a var is empty but exists
if(typeof testVar2 !== 'undefined' && testVar2 !== null){
if(testVar2 !== ''){
if(testVar2 === 'Hello'){
alert('testVar2 has a value! Value: ' + testVar2);
}{
alert('testVar2 has a value but it is not the one we expected.');
}
}{
alert('testVar2 does not have a value!');
}
}
// Test existance
if(typeof testVar3 !== 'undefined' && testVar3 !== null){
alert('testVar3 exists!');
}else{
alert('testVar3 does not exist!');
}

How to minimize the if statement in javascript

I have a very long if-conditional statement. How can I minimize it?
Here is my code,
if(this.refs.category.value.trim() != "" &&
this.refs.decisive_min.value.trim() != "" && this.refs.decisive_max.value.trim() != "" &&
this.refs.interactive_min.value.trim() != "" && this.refs.interactive_max.value.trim() != "" &&
this.refs.stabilizing_min.value.trim() != "" && this.refs.stabilizing_max.value.trim() != "" &&
this.refs.cautious_min.value.trim() != "" && this.refs.cautious_max.value.trim() != "" &&
this.refs.aesthetic_min.value.trim() != "" && this.refs.aesthetic_max.value.trim() != "" &&
this.refs.economic_min.value.trim() != "" && this.refs.economic_max.value.trim() != "" &&
this.refs.individualistic_min.value.trim() != "" && this.refs.individualistic_max.value.trim() != "" &&
this.refs.political_min.value.trim() != "" && this.refs.political_max.value.trim() != "" &&
this.refs.altruist_min.value.trim() != "" && this.refs.altruist_max.value.trim() != "" &&
this.refs.regulatory_min.value.trim() != "" && this.refs.regulatory_max.value.trim() != "" &&
this.refs.theoretical_min.value.trim() != "" && this.refs.theoretical_max.value.trim() != ""){
var data = {category:this.refs.category.value.trim()};
data.decisive_min = this.refs.decisive_min.value.trim();
data.decisive_max = this.refs.decisive_max.value.trim();
data.interactive_min = this.refs.interactive_min.value.trim();
data.interactive_max = this.refs.interactive_max.value.trim();
data.stabilizing_min = this.refs.stabilizing_min.value.trim();
data.stabilizing_max = this.refs.stabilizing_max.value.trim();
data.cautious_min = this.refs.cautious_min.value.trim();
data.cautious_max = this.refs.cautious_max.value.trim();
data.aesthetic_min = this.refs.aesthetic_min.value.trim();
data.aesthetic_max = this.refs.aesthetic_max.value.trim();
data.economic_min = this.refs.economic_min.value.trim();
data.economic_max = this.refs.economic_max.value.trim();
data.individualistic_max = this.refs.individualistic_max.value.trim();
data.individualistic_min = this.refs.individualistic_min.value.trim();
data.political_min = this.refs.political_min.value.trim();
data.political_max = this.refs.political_max.value.trim();
data.altruist_min = this.refs.altruist_min.value.trim();
data.altruist_max = this.refs.altruist_max.value.trim();
data.regulatory_min = this.refs.regulatory_min.value.trim();
data.regulatory_max = this.refs.regulatory_max.value.trim();
data.theoretical_min = this.refs.theoretical_min.value.trim();
data.theoretical_max = this.refs.theoretical_max.value.trim();
I just want to check all the values in the form if they are all not empty string.
I used refs by React JS in Meteor.
You could use an array with the wanted keys. Then take only one loop for assigning and checking.
If all values are truthy, data contains the trimmed values, otherwise it is undefined.
var keys = ['category', 'decisive_min', 'decisive_max', 'interactive_min', 'interactive_max', 'stabilizing_min', 'stabilizing_max', 'cautious_min', 'cautious_max', 'aesthetic_min', 'aesthetic_max', 'economic_min', 'economic_max', 'individualistic_min', 'individualistic_max', 'political_min', 'political_max', 'altruist_min', 'altruist_max', 'regulatory_min', 'regulatory_max', 'theoretical_min', 'theoretical_max'],
data = {};
data = keys.every(function (k) {
return data[k] = this.refs[k].value.trim();
}, this) && data || undefined;
Using ES2015, you can do something like that :
Inside your component
const fields = getFields(this.refs);
if (checkFieldsNotEmpty(fields)) {
const data = {category:this.refs.category.value.trim()};
fields.forEach(field => {
data[`${field.name}_min`] = field.valueMin;
data[`${field.name}_max`] = field.valueMax;
});
// ...
}
Outside your component (can be static methods)
const fieldNames = [
'decisive',
'interactive',
'stabilizing',
// ...
];
const getFields = refs => fieldNames.map(name => ({
name,
valueMin: refs[`${fieldName}_min`].value.trim(),
valueMax: refs[`${fieldName}_max`].value.trim()
}));
const checkFieldsNotEmpty = fields => {
for (let field of fields) {
if (field.valueMin === '' || field.valueMax === '') {
return false
}
}
return true;
};
Try using
for (var property in this.refs) {
if (this.refs.hasOwnProperty(property)) {
// perform a null check
if(this.refs[property]){
//perform operaion
data[property] = this.refs[property].trim();
}
}
}

Javascript validate empty fields

Can anyone help me on how to validate the javascript form if the
following fields are empty? It doesn't seem to work for my code.
function addvalidation(){
var w = document.forms["shop"]["w"].value;
var t = document.forms["shop"]["t"].value;
var a = document.forms["shop"]["a"].value;
var c = document.forms["shop"]["c"].value;
var s = document.forms["shop"]["s"].value;
var c = document.forms["shop"]["c"].value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}
http://jsfiddle.net/tn2fvh4p/91/
http://jsfiddle.net/tn2fvh4p/68/
Please use following code
function addvalidation(){
var w = document.getElementById("w").value;
var t = document.getElementById("t").value;
var a = document.getElementById("a").value;
var c = document.getElementById("c").value;
var s = document.getElementById("s").value;
var c = document.getElementById("c").value;
if (w == "" || t =="" || a == ""|| c == "" || s == "" || c == "") {
alert("Mandatory fields must be filled out");
return false;
}

Categories

Resources