Divide a function value by a number - javascript

I want to be able to take the value from the calcOrderTotal input and then divide it and display the divided output in another input (for example, to show the Order Total price, and then what the order total 36 monthly lease price would be). I sort of attempted to do it with the "calc36Month" function, but I know it's not right.
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
}
The calcOrderTotal function is then redirected to this HTML input and displays a dollar value (this does work):
<input type="text" class="total-box" value="$0" id="order-total" disabled="disabled" name="order-total"></input>
I want to be able to take the OrderTotal dollar value and divide it by 36 months and input the 36 month lease value into another input. Here is an example of what I'm looking for (I know this does not work):
function calc36Month() {
var 36Month = 0;
var orderTotal = $("#order-total").val() || 0;
var 36Month = parseFloat(CleanNumber(orderTotal)) / 36;
$("#36-monthly-total").val(CommaFormatted(36Month));
$("#fc-price").attr("value", 36Month);
}
How can I do this?

Here ya go:
function calcOrderTotal() {
var orderTotal = 0;
var productSubtotal = $("#product-subtotal").val() || 0;
var serverPrice = $('.server-radio:checked').val() || 0;
var equipmentPrice = $('.equipment-radio:checked').val() || 0;
var underTotal = $("#under-box").val() || 0;
var orderTotal = parseFloat(CleanNumber(productSubtotal)) + parseFloat(CleanNumber(serverPrice)) + parseFloat(CleanNumber(equipmentPrice));
$("#order-total").val(CommaFormatted(orderTotal));
$("#fc-price").attr("value", orderTotal);
if (orderTotal > 0) {
calcMonthly(orderTotal);
}
}
EDIT: Edited per request.
function calcMonthly(total) {
var pmt1 = total / 36;
var pmt2 = total / 24;
var pmt3 = total / 12;
$("#monthly-36").val(CommaFormatted(pmt1));
$("#monthly-24").val(CommaFormatted(pmt2));
$("#monthly-12").val(CommaFormatted(pmt3));
//$("#fc-price").attr("value", pmt1); // what is the purpose of this?
}
Avoid using numeric digits as variable names, element ID's or CSS classes, or beginning any of the aforementioned references with a number. Begin all variable names, ID's and classes with a letter.

Related

How to automate randomizing 46 names to create 46 x 6 unique rows and columns in Google sheet?

I am working with automation in Google sheet. Can you help me?
This problem is for sending surveys to 46 people. Each people needs to rate 5 people from those 46 people.
Requirements:
1. 1 rater, for 5 uniques ratees
2. No duplicate name per row (it should be 6 unique names in a row)
3. No duplicate name per column (it should be 46 unique names per column)
Expected output is for us to create 46x6 random names with no duplicates in row and columns.
-
-
Flow:
If a unique matrix across and below can be created, then it's values can be used as keys to the actual name array.
Create a 2D number array with length = number of rows
Loop through required number of columns and rows
Create a temporary array (tempCol) to store current column data
Fill the array with random numbers
Use indexOf to figure out if any random numbers are already present in the currentrow/ current column, if so, get a new random number.
In random cases, where it's impossible to fill up the temporary column with unique random numbers across and below, delete the temporary column and redo this iteration.
Snippet:
function getRandUniqMatrix(numCols, numRows) {
var maxIter = 1000; //Worst case number of iterations, after which the loop and tempCol resets
var output = Array.apply(null, Array(numRows)).map(function(_, i) {
return [i++]; //[[0],[1],[2],...]
});
var currRandNum;
var getRandom = function() {
currRandNum = Math.floor(Math.random() * numRows);
}; //get random number within numRows
while (numCols--) {//loop through columns
getRandom();
for (
var row = 0, tempCol = [], iter = 0;
row < numRows;
++row, getRandom()
) {//loop through rows
if (//unique condition check
!~output[row].indexOf(currRandNum) &&
!~tempCol.indexOf(currRandNum)
) {
tempCol.push(currRandNum);
} else {
--row;
++iter;
if (iter > maxIter) {//reset loop
iter = 0;
tempCol = [];
row = -1;
}
}
}
output.forEach(function(e, i) {//push tempCol to output
e.push(tempCol[i]);
});
}
return output;
}
console.info(getRandUniqMatrix(6, 46));
var data1d = data.map(function(e){return e[0]});
var finalArr = getRandUniqMatrix(6, 46).map(function(row){return row.map(function(col){return data1d[col]})});
destSheet.getRange(1,1,finalArr.length, finalArr[0].length).setValues(finalArr);
The OP wants to create a review matrix in which the names of the reviewed employees are chosen at random, the reviewer cannot review themselves, and the matrix is completed for 46 employees.
Based on previous code, this version builds an array of employee names for each row, in which the name of the reviewer is not included in the array. Five names are chosen at random and applied to the reviewer. The loop then repeats through each of the 46 employees.
For example, in the first round of reviews, "name01" is omitted from the array of employees from which the "reviewees" are randomly chosen. In the second round, "name01" is included, but "name02" is excluded from the array of employees. And so on, such that in each case, the array of employees used for the random selection of five reviews is always 45 names in length, and excludes the name of the reviewer.
The random selection of names to be rated does not ensure an equal and even distribution of reviews among employees. Though each employee will conduct 5 reviews, some employees are reviewed more than 5 times, some less than 5 times, and (depending on the alignment of the sun, the moon and the stars) it is possible that some may not be selected for review.
function s05648755803(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetname = "Sheet3";
var sheet = ss.getSheetByName(sheetname);
// some variables
var randomcount = 30; // how many random names
var rowstart = 7; // ignore row 1 - the header row
var width = 5; // how many names in each row - 1/rater plus 5/ratee
var thelastrow = sheet.getLastRow();
//Logger.log("DEBUG:last row = "+thelastrow)
// get the employee names
var employeecount = thelastrow-rowstart+1;
//Logger.log("DEBUG: employee count = "+employeecount);//DEBUG
// get the data
var datarange = sheet.getRange(rowstart, 1, thelastrow - rowstart+1);
//Logger.log("DEBUG: range = "+datarange.getA1Notation());//DEBUG
var data = datarange.getValues();
//Logger.log("data length = "+data.length);
//Logger.log(data);
var counter = 0;
var newarray = [];
for (c = 0;c<46;c++){
counter = c;
for (i=0;i<data.length;i++){
if(i!=counter){
newarray.push(data[i]);
}
}
//Logger.log(newarray);
var rowdata = [];
var results = selectRandomElements(newarray, 5);
Logger.log(results)
rowdata.push(results);
var newrange = sheet.getRange(rowstart+c, 3, 1, 5);
newrange.setValues(rowdata);
// clear the arrays for the next loop
var newarray=[];
var rowdata = []
}
}
/*
// selectRandomElements and getRandomInt
// Credit: Vidar S. Ramdal
// https://webapps.stackexchange.com/a/102666/196152
*/
function selectRandomElements(fromValueRows, count) {
var pickedRows = []; // This will hold the selected rows
for (var i = 0; i < count && fromValueRows.length > 0; i++) {
var pickedIndex = getRandomInt(0, fromValueRows.length);
// Pick the element at position pickedIndex, and remove it from fromValueRows. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
var pickedRow = fromValueRows.splice(pickedIndex, 1)[0];
// Add the selected row to our result array
pickedRows.push(pickedRow);
}
return pickedRows;
}
function getRandomInt(min,
max) { // From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
Screenshot#1
Screenshot#2
Try this. Satisfies all the three requirements.
HTML/JS:
<html>
<title>Unique Employees</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<table id="survey_table" border="1" width="85%" cellspacing="0">
<thead>
<th>Rater</th>
<th>Ratee1</th>
<th>Ratee2</th>
<th>Ratee3</th>
<th>Ratee4</th>
<th>Ratee5</th>
</thead>
<tbody id="table_body">
</tbody>
</table>
<script type="text/javascript">
function arrayRemove(arr, value) {
return arr.filter(function(ele) {
return ele != value;
});
}
function getRandomInt(rm_row, rm_col) {
var temp_arr = [];
for (var k = 1; k <= 46; k++) {
temp_arr.push(k);
}
for (var k = 0; k < rm_row.length; k++) {
temp_arr = arrayRemove(temp_arr, rm_row[k]);
}
for (var k = 0; k < rm_col.length; k++) {
temp_arr = arrayRemove(temp_arr, rm_col[k]);
}
var rand = temp_arr[Math.floor(Math.random() * temp_arr.length)];
return rand;
}
function exclude_num(row_unq, col_unq) {
var rand_int = getRandomInt(row_unq, col_unq);
if (!row_unq.includes(rand_int) && !col_unq.includes(rand_int)) {
arr_row.push(rand_int);
return rand_int;
} else {
return exclude_num(arr_row, arr_cols);
}
}
for (var i = 1; i <= 46; i++) {
var arr_row = [];
arr_row.push(i);
var table_html = '<tr id="Row' + i + '">';
for (var j = 1; j <= 6; j++)
{
if (j == 1) {
table_html += '<td class="Column' + j + ' cells_unq">' + i + '</td>';
} else {
var arr_cols = []
$('.Column' + j).each(function() {
arr_cols.push(Number($(this).text()));
});
var num = exclude_num(arr_row, arr_cols);
table_html += '<td class="Column' + j + ' cells_unq">' + num + '</td>';
}
}
table_html += '</tr>';
var row_html = $('#table_body').html();
$('#table_body').html(row_html + table_html);
}
$('.cells_unq').each(function() {
temp_text = $(this).text();
$(this).text('Name' + temp_text);
});
</script>
<style type="text/css">
td {
text-align: center;
}
</style>
</html>

Problems averaging

I have the following function in javascript to calculate the average:
function calculaMediaFinal () {
var soma = 0;
for(var i = 1; i>5; i++) {
soma += parseInt(document.getElementById('resultado' + i).value, 10);
}
var media = soma / 5;
var inputCuboMedia = document.getElementById('ConcretizaObj');
inputCuboMedia.value = parseInt(media, 10);
}
function ContarObjetivos() {
let contador = 0;
if(document.getElementById('resultado' + i).value) {
contador++;
}
}
But I have a problem, it's that I put in that at most there are 5 which is not true, because the user is who chooses how many results he wants. That is, the 5 can not be filled if the user only wants 4. How do I average without the number 5 but with the number of results that the user wants?
You can do it like this.
create input element and let user pass each number into it separated by space
create button that will trigger the code that calculates the average
create element that will store the result
To perform the actual computation
get value of input field, split it at space ' ', remove white spaces around each separate number using trim
sum the array created in the previous step using reduce
divide the sum by the amount of provided numbers
const input = document.querySelector('input');
const btn = document.querySelector('button');
const res = document.querySelector('p > span');
function getAverage() {
const values = input.value.split(' ').map(v => v.trim());
const sum = values.reduce((acc, v) => acc + Number(v), 0);
res.textContent = (sum / values.length);
}
// 1 2 3 4 5 6 7 8 9 10
btn.addEventListener('click', getAverage);
<input type='text' />
<button>get average</button>
<p>result: <span></span></p>
Where you pass numbers into input field one by one separated by space (try passing 1 2 3 4 5 6 7 8 9 10) and then click button to perform the computation which then will be shown in span element.
Your loop wasn't executed:
In a for, the second parameter is the condition for which the iteration is going to be executed (true = execute). Changing > to <= made it work.
I also merged your two functions so that a not filled input doesn't count.
Here is a working snippet where I used all your code:
// Merged both function:
function calculaMediaFinal() {
let soma = 0;
let contador = 0;
for (var i = 1; i <= 5; i++) { // Changed > to <= here
if (document.getElementById('resultado' + i).value) {
soma += parseInt(document.getElementById('resultado' + i).value, 10);
contador++;
}
}
var media = soma / contador;
var inputCuboMedia = document.getElementById('ConcretizaObj');
inputCuboMedia.value = parseInt(media, 10);
}
<input id="resultado1"><br>
<input id="resultado2"><br>
<input id="resultado3"><br>
<input id="resultado4"><br>
<input id="resultado5"><br>
<button onclick="calculaMediaFinal();">calcula</button>
<br> Media:
<input id="ConcretizaObj">
⋅
⋅
⋅
If you don't need to specify the "base" in the parseInt function, I also suggest you to use the unary + operator:
// Merged both function:
function calculaMediaFinal() {
let soma = 0;
let contador = 0;
for (var i = 1; i <= 5; i++) { // Changed > to <= here
if (document.getElementById('resultado' + i).value) {
soma += +document.getElementById('resultado' + i).value;
contador++;
}
}
var media = soma / contador;
document.getElementById('ConcretizaObj').value = media;
}
<input id="resultado1"><br>
<input id="resultado2"><br>
<input id="resultado3"><br>
<input id="resultado4"><br>
<input id="resultado5"><br>
<button onclick="calculaMediaFinal();">calcula</button>
<br> Media:
<input id="ConcretizaObj">
Hope it helps.
If I understand your question correct, you want something like this. Create a new numeric input field that stores the amount that the user wants. Put the value of the input field in a variable and use it in your code? Also it probably needs to be '<=' in the for loop to be executed. For example
HTML add next line in your code:
<input type="number" id="userAmount" />
Javascript:
function calculaMediaFinal () {
var soma = 0;
var amount = parseInt(document.getElementById("userAmount").value);
for(var i = 1; i<=amount; i++) {
soma += parseInt(document.getElementById('resultado' + i).value, 10);
}
var media = soma / amount;
var inputCuboMedia = document.getElementById('ConcretizaObj');
inputCuboMedia.value = parseInt(media, 10);
}
function ContarObjetivos(){
let contador = 0;
if(document.getElementById('resultado' + i).value) {
contador++;
}
}

Shift letters from input to the next in alpabhet

I have been searching the web and I have found a few examples about my current problem, and all seems to be addressing the same topic: deciphering text. But I cannot find anything written in javascript. I gave it a shot, but I'm stuck when trying to convert the string in to an array.
Lets say that the current alphabet is
var alpabhet=[
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö'
];
And I have a string ammj, that I enter in the input. Then I want to be able to shift with right and left key and view the output of that current shift. So a shift of two (2) would result in the string cool. And a shift of 5 for the string åjjg would also result in cool.
So my main concern is, how can I convert a user input to an array with javascript?
I have a input filed:<input id="text_to_be_shifted" type="text"> and then I'm trying to loop the input and arrange into a array
var values = {};
var inputs = document.getElementById('text_to_be_shifted');
for( var i = 0; i < inputs.length; i++ ) {
values[inputs[i].name] = inputs[i].value;
}
Have a look at my fiddle: http://jsfiddle.net/p8kqmdL1/
Here you have a live and working example, with a check so that shifting letter 'a' with -1 will convert it to last letter of the alphabet 'ö', -2 to 'ä' e.t.c. and shifting last letter of alphabet with 1 will set it to 'a', with 2 to 'b' e.t.c:
var alpabhet=[
'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','å','ä','ö'
];
var values = {};
var inputs = document.getElementById('text_to_be_shifted');
for( var i = 0; i < inputs.length; i++ ) {
values[inputs[i].name] = inputs[i].value;
}
function outputText(number){
var newtext = [];
var inputtext = document.getElementById('text_to_be_shifted').value.split('');
inputtext.forEach(letter=> {
var ind_ofLetter = alpabhet.indexOf(letter);
ind_ofLetter = ind_ofLetter + number;
if (ind_ofLetter < 0){
ind_ofLetter = alpabhet.length + ind_ofLetter;
}else if(ind_ofLetter > alpabhet.length-1){
ind_ofLetter = ind_ofLetter - alpabhet.length;
}
newtext.push(alpabhet[ind_ofLetter]);
});
document.getElementsByClassName('output')[0].innerHTML = newtext.join('');
}
function shiftUp() {
var currentShift = document.getElementById('currentShift');
var number = currentShift.innerHTML;
number++;
currentShift.innerHTML = number;
outputText(number);
}
function shiftDown() {
var currentShift = document.getElementById('currentShift');
var number = currentShift.innerHTML;
number--;
currentShift.innerHTML = number;
outputText(number);
}
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == '37') {
console.log('left arrow')
shiftDown()
}
else if (e.keyCode == '39') {
console.log('right arrow')
shiftUp()
}
}
<b>Current shift: </b><span id="currentShift">0</span>
<br><input id="text_to_be_shifted" type="text">
<div id='output' class="output"></div>
There is only one input, so there is no point in looping over it.
To get an array, you should use something like:
document.getElementById('text_to_be_shifted').split("");
You can then use the map function to shift the elements
let arr = document.getElementById('text_to_be_shifted').split("");
let shifted = arr.map((c) => alpabhet[(alpabhet.indexOf(c) + 1) % alpabhet.length]).join("");
in your for loop you can utilize the charAt() function to get the individual character at a given index. W3 schools has a good lesson on this function if needed: https://www.w3schools.com/jsref/jsref_charat.asp
var inputArray = [];
var inputs = document.getElemenById('text_to_be_shifted');
for(let i = 0; i < inputs.length; i++){
inputArray[i] = inputs.charAt(i);
}
Something like this should work to get you an array with a single letter at each index.

Setting up Javascript order price minimum

I am trying to set up a way so that if my total cart's price is under $125, it will charge $125. I have googled multiple ways of getting the order minimum added but nothing works with how this code was set up. Please view the code below:
function Recalculate() {
var total = 0;
$.each(cart, function(index, item) {
var options = {};
if (item.o) $.each(item.o, function(opt_ind, opt_item) {
options[opt_item.name] = opt_item.value;
options[opt_item.id] = opt_item.value;
});
var width_ft = parseInt(options.width_ft);
if (!width_ft || isNaN(width_ft)) width_ft = 0;
var width_in = parseInt(options.width_in);
if (!width_in || isNaN(width_in)) width_in = 0;
var width = width_ft + width_in / 12;
var length_ft = parseInt(options.length_ft);
if (!length_ft || isNaN(length_ft)) length_ft = 0;
var length_in = parseInt(options.length_in);
if (!length_in || isNaN(length_in)) length_in = 0;
var sq = width * length;
var inshop = options.type_of_cleaning == 'In_Shop_Cleaning';
var base_price = 0;
var base_min = 0;
switch (item.p) {
case 'livingroom':
base_price = LIVING_ROOM;
break;
case 'stair':
base_price = STAIR;
break;
}
var i_total = sq * base_price;
if (i_total < base_min) i_total = base_min;
$('span.isize').eq(index).html('$' + i_total.toFixed(2));
total += i_total;
if (options.SCOTCHGARD == 'on') total += Math.min(sq * SCOTCHGARD, 25.00);
if (options.DECON == 'on') total += Math.min(sq * DECON, 25.00);
if (options.DA == 'on') total += Math.min(sq * DA, 25.00);
if (options.clean_or_buy == 'buy') total += i_total * NEW_PAD_TAX / 100;
});
return [total];
}
If you want to charge a minimum of $125, the simplest thing you could do is simply set the total to that minimum just before you return it. e.g.
if (total < 125) { total = 125; }
return total;
(Note that this is returning total not [total], as it is not clear to me why you want an array of a single value returned.)
Your question includes the phrase "...getting the order minimum added". That doesn't make sense to me, i.e. if the real total is $100, I doubt that you want to add $125 (to make $225 total), but rather you simply want to set the total to the minimum. If that is correct, but you do want to keep track of the extra that you add, then perhaps you could do the following, again right before you return from the function:
var extraForMinimum = 0;
if (total < 125) { extraForMinimum = 125 - total; }
return {total: total, extraForMinimum: extraForMinimum };
In this case, the function is returning an object that contains both the actual total (which could still be less than $125) as well as the extra cost that is required to bring the charge up to the minimum. If you are doing this, however, you might want to change the variable name from total to, say, subtotal or something else similar.

How to get the textbox value when dropdown box value changed in javascript

I am having the
table which contains the table like
items  price  quantity  total
apple    100     2         200
orange  200    2           600
grand total=600.
item fields are dropdown when drop down changes the price will be changed and total value and grandtotal also changed. My problem is when selecting apple and orange again go to apple change the item my grand total is not changing.
My Javascript code:
function totalprice(element, price) {
var elementid = element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:" + expr).value;
var price = document.getElementById("price:" + expr).value;
if (quantity > 0) {
document.getElementById("total:" + expr).value = (parseInt(quantity)) * (parseInt(price));
var grandtotal = document.getElementById("total:" + expr).value;
var gtot = 0;
var amount = 0;
for (var i = 0; i <= expr; i++) {
//document.getElementById("total").value="";
gtot = document.getElementById("total:" + expr).value;
amount = parseInt(gtot) + parseInt(amount);
}
document.getElementById("total").value = amount;
}
return true;
}
I know the mistake is in for loop only it is simple one but i dont know how to solve.
I got the solution for this using table rows length and use that length to my for loop now my code is like
function totalprice(element,price)
{
var elementid=element.id;
var expr = elementid.substring(elementid.indexOf(":") + 1, elementid.length);
var quantity = document.getElementById("quantity:"+expr).value;
var price = document.getElementById("price:" + expr).value;
if(quantity >0)
{
document.getElementById("total:"+ expr ).value= (parseInt(quantity))*(parseInt(price));
//var grandtotal =document.getElementById("total:"+expr).value;
//var grandtotal = document.getElementsByClassName("total"+expr);
var rowcount = document.getElementById('table').rows.length;
var grandtotal = 0;
var finalamount = 0;
for(var i=1; i<rowcount; i++)
{
grandtotal=document.getElementById("total:"+i).value;
finalamount = parseInt(grandtotal) + parseInt(finalamount);
}
document.getElementById("total").value=finalamount;
}
return true;
}
Here is code what you need:
Java Script:
<script>
function getVal(e){
// for text
alert(e.options[e.selectedIndex].innerHTML);
// for value
alert(e.options[e.selectedIndex].value);
}
</script>
HTML:
<select name="sel" id="sel" onchange='getVal(this);'>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Cat</option>
</select>
I see two errors in your for loop, first you forgot to use i in your getElement so you're only going through the same field multiple times, second, you're only looping through the inputs previous to the field that was updated (i<=expr), when you actually want to go through all the "total" fields to get the grand total, I would suggest giving a class to all your total fields and then use this code for your loop
var total_fields = document.getElementsByClassName('total');
for (var i = 0; i < total_fields.length; i++) {
gtot = total_fields[i].value;
amount+= parseInt(gtot);
}
document.getElementById("total").value = amount;
I think the problem relies here:
"My problem is when selecting apple and orange again"
Because I don't see in your code that you are actually updating the elements id when you calculate the total.
So... If you do:
gtot = document.getElementById("total:" + expr).value;
First time will work, because expr var is the original one, then, gtot is the right element id
but...
...when you do a second change, that var has a different value now... and gtot will not match your element id to recalculate the new value. (or in worst case, will match another and update the wrong one)

Categories