Make calculation based on information provided - javascript

I am building a website and I want to do calculations based on information provided. I obviously need to have information provided in two out of the three fields to calculate the third's value.
The three fields are:
Price Per Gallon
Gallons Bought
Total Sale
I obviously know that I can calculate the amount of gas bought by dividing the Total Sale amount by the Price Per Gallon.
However I want to calculate based on whatever two fields are entered. I am trying to find out the best way to do this.
I know this much:
Check to see which fields are empty
Determine which type of calculation to make
Here is what I have so far:
<form>
<input type="number" id="totalSale" placeholder="Total Sale Amount" class="calculate" />
<input type="number" id="gallonPrice" placeholder="Price Per Gallon" class="calculate" />
<input type="number" id="gallons" placeholder="Gallons" class="calculate" />
</form>
<script>
var e = document.getElementsByClassName("calculate");
function calc(){
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
if (sale_amt || ppg !== null) {
var calc_gallons = sale_amt.value / ppg.value;
gallons.value = calc_gallons.toFixed(3);
}
}
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
}
</script>

the logic should take into consideration which element is currently being entered (that will be this in calc). Also, you need to take into consideration what happens when all three have values, and you change one ... which of the other two should be changed?
See if this works for you
var sale_amt = document.getElementById("totalSale");
var ppg = document.getElementById("gallonPrice");
var gallons = document.getElementById("gallons");
function calc(){
var els = [sale_amt, ppg, gallons];
var values = [sale_amt.value, ppg.value, gallons.value];
var disabledElement = els.find(e=>e.disabled);
var numValues = els.filter(e => e.value !== '' && !e.disabled).length;
var calc_gallons = function() {
gallons.value = (values[0] / values[1]).toFixed(3);
};
var calc_ppg = function() {
ppg.value = (values[0] / values[2]).toFixed(3);
};
var calc_sale = function() {
sale_amt.value = (values[1] * values[2]).toFixed(2);
};
if (numValues < 3) {
if (numValues == 1 && disabledElement) {
disabledElement.disabled = false;
disabledElement.value = '';
disabledElement = null;
}
els.forEach(e => e.disabled = e == disabledElement || (numValues == 2 && e.value === ''));
}
disabledElement = els.find(e=>e.disabled);
switch((disabledElement && disabledElement.id) || '') {
case 'totalSale':
calc_sale();
break;
case 'gallonPrice':
calc_ppg();
break;
case 'gallons':
calc_gallons();
break;
}
}
var e = document.getElementsByClassName("calculate");
for (var i = 0; i < e.length; i++) {
e[i].addEventListener('keyup', calc, false);
e[i].addEventListener('change', calc, false);
}

Related

How to implement an if-statement in an order form

I'm building a simple order form with some calculations with number & hidden fields (for email and autoresponder).
When the user input field is not '0' i want it to calculate the delivery cost in the total price. In the script below the Delivery cost always returns '0' even when the user field is not '0'.
If I change the value to a certain value it always returns that value even when the user field is '0'. So the IF is wrong somehow.
/* Get the values from the user*/
function getAantal() {
var AantalBoek = document.getElementById('AantalBoek').value;
var AantalCD = document.getElementById('AantalCD').value;
var AantalSoundtrack = document.getElementById('AantalSoundtrack').value;
/* Product variables*/
var PrijsBoek = document.getElementById('PrijsBoek').value;
var PrijsCD = document.getElementById('PrijsCD').value;
var PrijsSoundtrack = document.getElementById('PrijsSoundtrack').value;
/* Delivery variables, Soundtrack does not have delivery*/
/* in my logic the IF says: if user fills in 0 for AantalBoek,
then VerzendingBoek is 0 instead of 7. But it always returns 0, even if AantalBoek is 1*/
var VerzendingBoek = document.getElementById('VerzendingBoek').value;
if (AantalBoek !== null && AantalBoek !== '') {
VerzendingBoek = 0;
}
var VerzendingCD = document.getElementById('VerzendingCD').value;
if (AantalCD !== null && AantalCD !== '') {
VerzendingCD = 0;
}
/* Calculation of the Product total*/
var SubTotaalBoek = PrijsBoek * AantalBoek;
var SubTotaalCD = PrijsCD * AantalCD;
var SubTotaalSoundtrack = PrijsSoundtrack * AantalSoundtrack;
/* Calculation of the Delivery total*/
var TotaalVerzending = +VerzendingBoek + +VerzendingCD;
/* Calculation of the Final total*/
var Totaal = +SubTotaalBoek + +SubTotaalCD + +SubTotaalSoundtrack + +TotaalVerzending;
document.getElementById('Verzending').value = TotaalVerzending;
document.getElementById('TotaalPrijs').value = Totaal;
}
<!-- user defines values here: -->
<input type="number" id="AantalBoek" required="" onchange="getAantal()">
<input type="number" id="AantalCD" required="" onchange="getAantal()">
<input type="number" id="AantalSoundtrack" required="" onchange="getAantal()">
<!-- set values for the products: -->
<input type="hidden" id="PrijsBoek" name="PrijsBoek" value="15">
<input type="hidden" id="PrijsCD" name="PrijsCD" value="4">
<input type="hidden" id="PrijsSoundtrack" name="PrijsSoundtrack" value="2">
<!-- set values for the delivery cost: -->
<input type="hidden" id="VerzendingBoek" name="VerzendingBoek" value="7">
<input type="hidden" id="VerzendingCD" name="VerzendingCD" value="2">
<!-- totals are shown here (only for autorespond) -->
<input type="hidden" id="Verzending" name="Verzending">
<input type="hidden" id="TotaalPrijs" name="TotaalPrijs">
Ok i've started over, looking again at the if-statement and i found a syntax error, changed the condition and added an else statement.
The corrected script is this:
function getAantal(){
var AantalBoek = document.getElementById('AantalBoek').value;
var AantalCD = document.getElementById('AantalCD').value;
var AantalSoundtrack = document.getElementById('AantalSoundtrack').value;
var PrijsBoek = document.getElementById('PrijsBoek').value;
var PrijsCD = document.getElementById('PrijsCD').value;
var PrijsSoundtrack = document.getElementById('PrijsSoundtrack').value;
var VerzendingBoek = document.getElementById('VerzendingBoek').value;
/* Here I changed the condition: IF the user value is 0 then the delivery cost is 0,
ELSE use the value that was already defined:*/
if(AantalBoek == 0) { VerzendingBoek = 0;
} else {VerzendingBoek = document.getElementById('VerzendingBoek').value;
}
var VerzendingCD = document.getElementById('VerzendingCD').value;
if(AantalCD == 0) { VerzendingCD = 0;
} else {VerzendingCD = document.getElementById('VerzendingCD').value;
}
/*for the second condition i corrected the syntax error !== to !=,
IF delivery cost for Boek is not 0, then delivery cost for CD is 0*/
if (VerzendingBoek != 0) { VerzendingCD = 0;
}
var SubTotaalBoek = PrijsBoek * AantalBoek;
var SubTotaalCD = PrijsCD * AantalCD;
var SubTotaalSoundtrack = PrijsSoundtrack * AantalSoundtrack;
var TotaalVerzending = +VerzendingBoek + +VerzendingCD;
var Totaal = +SubTotaalBoek + +SubTotaalCD + +SubTotaalSoundtrack + +TotaalVerzending;
document.getElementById('Verzending').value=TotaalVerzending;
document.getElementById('TotaalPrijs').value=Totaal;
}

I stuck with this code, trying to figure out, how it should work

I'm working on a poject, need it must be auto calculation.
let say that we have uncounted hidden inputs with known same class and attr. diffrent value, attr diffrent price, price2 price 3 in a div to count
What im trying to do is to get attrs (price, priceX2, priceX3)
if the user inserted a number ex. 1 or 40, will return first input(price, priceX2, priceX3), and if its given 61 0r 70 then it will return to the third input(price, priceX2, priceX3) so on
<div id="countDiv">
<input type="number" value="" id="counter" />
<button id="countBtn"> Count </button>
<input type="hidden" value="40" price="1100" priceX2="1200" priceX3="1220" class="classeid">
<input type="hidden" value="60" price="1150" priceX2="1250" priceX3="1300" class="classeid">
<input type="hidden" value="70" price="1220" priceX2="1350" priceX3="1400" class="classeid">
</div>
<script>
$(document).ready(function(){
$("#countBtn").click(function(){
var parentDOM = document.getElementById("countDiv");
var classCounter = parentDOM.getElementsByClassName("classeid");
var counter = $("#counter").val();
for (var i = 0, n = classCounter.length; i < n; ++i) {
var mPrice = parseInt(classCounter[i].value);
var cPrice = parseInt(classCounter[i].getAttribute('price'));
var cPriceX2 = parseInt(classCounter[i].getAttribute('priceX2'));
var cPriceX3 = parseInt(classCounter[i].getAttribute('priceX3'));
}
});
});
</script>
Hope this code help you.
Do do it dynamically it's not better to do using the Hidden field if you have more than 3 input hidden field. The logic will be different in that case.
Considering only 3 hidden input fields then code looks as below:
HTML Code:
provide id to the each hidden input fields as first, second and third as written in the code.
JavaScript Code:
$("#countBtn").click(function(){
var counter = $("#counter").val();
if(counter > 0 && counter <= 40) {
var mprice = $("#first").val();
var cprice = $("#first").attr("price");
var cPriceX2 = $("#first").val("priceX2");
var cPriceX3 = $("#first").attr("priceX3");
}
else if(counter > 39 && counter <= 60) {
var mprice = $("#second").val();
var cprice = $("#second").attr("price");
var cPriceX2 = $("#second").val("priceX2");
var cPriceX3 = $("#second").attr("priceX3");
}
else {
var mprice = $("#third").val();
var cprice = $("#third").attr("price");
var cPriceX2 = $("#third").val("priceX2");
var cPriceX3 = $("#third").attr("priceX3");
}
}

Loop for tabbing

HI i am pretty new to javascript,
following is my scenario, i want to make a function in which i pass the value of 'n' for number of iterations. i am writing my test script in javascript.
var tab6 = browser.actions().sendKeys(protractor.Key.TAB);
tab6.perform();
page.pause(3);
var tab7 = browser.actions().sendKeys(protractor.Key.TAB);
tab7.perform();
page.pause(3);
var tab8 = browser.actions().sendKeys(protractor.Key.TAB);
tab8.perform();
page.pause(3);
var tab9 = browser.actions().sendKeys(protractor.Key.TAB);
tab9.perform();
page.pause(3);
var tab10 = browser.actions().sendKeys(protractor.Key.TAB);
tab10.perform();
page.pause(3);
var tab11 = browser.actions().sendKeys(protractor.Key.TAB);
tab11.perform();
page.pause(3);
is this what you want ?
function performTab(n) {
for (var i = 0; i < n; i++) {
var tab = browser.actions().sendKeys(protractor.Key.TAB);
tab.perform();
page.pause(3);
}
}
If not, please, be more precise.
You want to count how many times you press tab, following a predetermined direction?
i'm really having a hardtime understanding what you want.
document.onkeypress = tabCount;
var ix = 0;
function tabCount(e){
var charCode = (typeof event.which == "number") ? event.which : event.keyCode
if (charCode == 9) ix++;
}
<input type=button tabIndex=1>
<input type=button tabIndex=2>
<input type=button tabIndex=3>
<input type=button tabIndex=4>
<input type=button tabIndex=5>
in context of test scenario, I'd do:
function testTabs( n )
{
for ( let i = 1; i <= n; i++ )
{
it(`Select tab #{i}`, () => {
browser.actions().sendKeys( protractor.Key.TAB ).perform();
page.pause(3);
};
};
}

JavaScript Calculating wrong

I am trying to perform calculation using JavaScript. When user enter less than 10 pages in input (#page) the cost is 1. if he adds more than 10, each page costs .10. there are 2 options for checkbox, if he clicks first checkbox 10 is added and second checkbox 15 is added.
This is working when it is done in sequential steps. (input then clicking checkbox).
Ex: Input is : 9 (total: 1)
click checkbox1 - duplicates (total : 11)
click checkbox1 - laser (total: 26)
Now if i change the Input to 11, then the total becomes 1.10 - even if both the checkboxes are checked.. (expected result should be - 26.10)
I am not sure how to do this...can anyone help me out
<html>
<head>
<title>Calculation</title>
<script>
function calculate() {
var pages=document.getElementById("page").value;
if(pages <=10) {
total.value=1;
}
if(pages >= 11) {
var extra_pages= pages - 10;
var new_total= extra_pages * .10;
var new_total1= 1 + new_total;
total.value= new_total1;
}
}
function checkbox1() {
if(document.getElementById("ckbox1").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 10;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox1").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 10;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
function checkbox2() {
if(document.getElementById("ckbox2").checked === true) {
var total1=document.getElementById("total").value;
const add1 = 15;
var check1 = +total1 + +add1;
total.value=check1;
}
if(document.getElementById("ckbox2").checked === false) {
var total1=document.getElementById("total").value;
const sub1 = 15;
var check2 = +total1 - +sub1;
total.value = check2;
}
}
</script>
<body>
Enter a Number: <input type="text" id="page" value="1" oninput="calculate()">
<br>
<br><br><br><br>
duplicates <input type="checkbox" id="ckbox1" onclick="checkbox1()">
laser print: <input type="checkbox" id="ckbox2" onclick="checkbox2()"> <br><br>
Total: <input type="text" id="total">
</body>
</html>
You can use calculate for all changes instead of creating each one for each input, which makes the calculation complex.
// Get reference to inputs.
var page = document.getElementById("page");
var total = document.getElementById("total");
var dup = document.getElementById("ckbox1");
var laser = document.getElementById("ckbox2");
function calculate() {
// To Number
var pages = parseInt(page.value, 10);
var value = 0;
if (pages <= 10) {
value = 1;
} else {
var extra_pages = pages - 10;
var new_total = extra_pages * .10;
var new_total1 = 1 + new_total;
value = new_total1;
}
// Add 10 if dup is checked.
if (dup.checked) {
value += 10;
}
// Add 15 if laser is checked.
// These can be moved out like
// const laserVal = 15;
// value += laserVal if you don't want magic number here.
if (laser.checked) {
value += 15;
}
// Truncate float.
total.value = value.toFixed(1);
}
Enter a Number:
<input type="text" id="page" value="1" oninput="calculate()">
<br>
<br>
<br>
<br>
<br>
duplicates:<input type="checkbox" id="ckbox1" onclick="calculate()">
laser print:<input type="checkbox" id="ckbox2" onclick="calculate()">
<br>
<br>Total:
<input type="text" id="total">

Unable to call function within jQuery

I am trying to call a function in this javascript code. My code needs to check for whether the user selects var num, var letters and var symbols to be true or false. In the code, I preset the values but I still search the object choices for the variables that are true and push it into the array choices_made. However, since I need to randomly choose the order in which the num, letters and symbols appear, I randomly choose the class based on the Math.random(). However, it doesn't show me the alert(jumbled_result) afterwards.
http://jsfiddle.net/bdaxtv2g/1/
HTML
<input id="num" type="text" placeholder="Enter desired length">
<br/><br/>
<input id="press" type="button" value="jumble it up">
JS
$(document).ready(function(){
var fns={};
$('#press').click(function(){
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
function gen(len, num, letters, sym){
var choices = {
1:num,
2:letters,
3:sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for(x in choices){
if(choices[x]==true){
choice_made.push(x);
}
}
for(i=0;i<len;i++){
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length-1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result){
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
});
You never declare functions within document.ready of jQuery. The functions should be declared during the first run(unless in special cases).
Here is a working code made out of your code. What I have done is just removed your functions out of document.ready event.
$(document).ready(function() {
$('#press').click(function() {
var length = parseInt($('#num').val());
var num = true;
var letters = true;
var symbols = false;
gen(length, num, letters, symbols);
});
});
var fns = {};
function gen(len, num, letters, sym) {
var choices = {
1: num,
2: letters,
3: sym
};
var choice_made = ['0'];
var choice = 0;
var jumbled_result = '';
for (x in choices) {
if (choices[x] == true) {
choice_made.push(x);
}
}
for (i = 0; i < len; i++) {
var funName = 'choice';
choice = Math.round(Math.random() * (choice_made.length - 1));
funName += choice_made[choice];
jumbled_result = fns[funName](jumbled_result);
}
alert(jumbled_result);
}
fns.choice0 = function choice0(jumbled_result) {
var numbers = '0123456789';
return jumbled_result += numbers.charAt(Math.round(Math.random() * numbers.length));
}
fns.choice1 = function choice1(jumbled_result) {
var alpha = 'abcdefghijklmnopqrstuvwxyz';
return jumbled_result += alpha.charAt(Math.round(Math.random() * alpha.length));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="num" type="text" placeholder="Enter desired length">
<br/>
<br/>
<input id="press" type="button" value="jumble it up">
Its because of the way the object choices have been intitialized.. Try this..
var choices = {
0:num,
1:letters,
2:sym
};
And also
var choice_made = [];
JS fiddle link : http://jsfiddle.net/8dw7nvr7/2/

Categories

Resources