I have a small "problem". I try to do a Loop-for for a
"getElementsByName" for each rows in the table.
I try to loop a few values.
Price * Quantity * discount * tax (select.options) = MY Final price after discout.
AD: (You have to open Full View)
For a single line it works great by getElementById. However, the need for the creation of the next line (Button Add Position). So i chose GetElementsByName
Also counted for him the value (in place "after rebate")
--EDIT--
I made a loop "For".
In html code I have a lot the same fields "named" (ex. cena, ile, rabat etc.)
So if I will had 3 rows with this fields I want to calculate for each line separately. But my loop doesn't work.
Full View you can see here:
http://codepen.io/warhero/pen/WwvLZE (121 line JS)
My JS code:
var i;
for (i = 0; i < document.getElementsByName('kwotarabat').length; i++) {
var cena = parseInt(document.getElementsByName('cena')[i].value);
var ile = parseInt(document.getElementsByName('ile')[i].value);
var rabat = parseInt(document.getElementsByName('rabat')[i].value);
var vat = document.getElementsByName('vat')[i].options[document.getElementsByName('vat')[i].selectedIndex].value;
// vat value
var wynik = (ile * cena * vat);
// the net value
var wynik2 = cena * ile;
// net amount after discount
var wynikRabat = (wynik2 * (rabat / 100));
// gross amount after discount
var wynikRabatVat = (wynik * (rabat / 100));
// net amount after discount (display for customers)
var wynikNetto = (wynik2 - wynikRabat);
document.getElementsByName('kwotarabat')[i].innerHTML = (wynik + wynik2 - wynikRabat - wynikRabatVat).toFixed(2);
}
In Here >> http://codepen.io/warhero/pen/ONVEmZ is the code for a single row and calculations are correct.
Any Ideas ?
Related
This code below creates a random costumer number and prints it out with a simple console log, but one feature is missing: It should check if the same costumer number/ID has already been generated before. If so, it should walk through the process again, so a new random number is generated which then is unique. How can I do that with this code? As a programming newbie I unfortunately have NO clue how I could do that. Maybe a while loop and storing the generated number in a variable? Would be totally awesome if you can provide the code, combined with mine or build in the duplicate-checking feature.
function generateCostumerNum() {
// generating a random 8-digit number with numbers from 1 to 9
var zeroToNine = "";
for (counter = 0; counter <= 7; counter++) {
var randomNumber = Math.floor(Math.random() * 9) + 1;
zeroToNine += randomNumber;
}
// calculating the cross-sum of the generated number above
var numberforCrossSum = zeroToNine,
crossSum = 0;
while (numberforCrossSum) {
crossSum += numberforCrossSum % 10;
numberforCrossSum = Math.floor(numberforCrossSum / 10);
}
// building together the final costumer ID string.
var finalCostumerNum = "ID" + zeroToNine + crossSum;
console.log(finalCostumerNum);
};
generateCostumerNum();
You can use a simple while loop that runs as long as the generated number has already been generated:
var already_generated_nums = []; // an array of the numbers already generated
//...
var new_num = generateCostumerNum();
while (already_generated_nums.includes(new_num)) {
new_num = generateCostumerNum();
}
already_generated_nums.push(new_num);
I have a button that dynamically creates 2 inputs per click
Data of Input 1: string
Data of Input 2: number (float) (0-100)
I am creating an array of each like this.
var recipe_flavour_name = $("input[name='flav-name']").map(function() {return $(this).val();}).get();
var recipe_flavour_percent = $("input[name='flav-percent']").map(function(){return $(this).val();}).get();
As far as I can tell, the arrays are comma separated values.
Let's for simplicity's sake say:
recipe_flavour_name = a,b,c
recipe_flavour_percent = 5,6,7
I then want to take the number value to use in a function and then loop through all the values and use jQuery's .html() to add the values to a div.
I have tried this: flavPercent1 is just recipe_flavour_percent
var arrayLength = flavPercent1.Length;
for (var i = 0; i < arrayLength; i++) {
var flavML = (flavPercent1[0] / 100 * 100 * 1000) / 1000;
var flavGrams = (flavML * .98 * 100) / 100;
var flavPercent = (flavML / 100 * 1E4) / 100;
$('.live-flavours').html('<tr>'+flavName[0]+'<td></td>'+parseFloat(flavML).toFixed(2)+'<td>'+parseFloat(flavGrams).toFixed(2)+'</td><td>'+parseFloat(flavPercent1[0]).toFixed(2)+'</td></tr>');
};
But I only get flavGrams and flavPercent returned, dynamically adding more data to the array does nothing.
What do I want to achieve?
Grab the values of specified inputs in an array.
Pass them to a function.
Loop through the values and output them in HTML using jQuery.
I hope that makes sense and thanks in advance.
Ok, so assuming that you don't have a problem getting the arrays you need, the problem lies within your for loop.
YOUR CODE:
for (var i = 0; i < arrayLength; i++) {
var flavML = (flavPercent1[0] / 100 * AMOUNT * 1000) / 1000;
var flavGrams = (flavML * .98 * 100) / 100;
var flavPercent = (flavML / AMOUNT * 1E4) / 100;
$('.live-flavours').html('<tr>'+flavName[0]+'<td></td>'+parseFloat(flavML).toFixed(2)+'<td>'+parseFloat(flavGrams).toFixed(2)+'</td><td>'+parseFloat(flavPercent1[0]).toFixed(2)+'</td></tr>');};
You put everything in the for loop, yet make no reference to the index. I'm assuming everywhere you put [0] you actually want [i]. This means that every time the index increases, you are getting the next array element.
You should use .append instead of .html. .html means that the current html will be replaced by what you are adding.
Finally, although making it dynamic is possible, I'm not sure that JQuery is the best libary to use in this case. I'd suggest taking a look at libraries such as Vue or MoonJs (both are very light and very simple libraries) etc... to find a much easier, and frankly better way to do this. They allow for dynamic rendering, and what you are trying to do becomes insanely simplified.
Hope this helps.
(hopefully) WORKING CODE:
for (var i = 0; i < arrayLength; i++) {
var flavML = (flavPercent1[i] / 100 * AMOUNT * 1000) / 1000;
var flavGrams = (flavML * .98 * 100) / 100;
var flavPercent = (flavML / AMOUNT * 1E4) / 100;
$('.live-flavours').append('<tr>'+flavName[i]+'<td></td>'+parseFloat(flavML).toFixed(2)+'<td>'+parseFloat(flavGrams).toFixed(2)+'</td><td>'+parseFloat(flavPercent1[i]).toFixed(2)+'</td></tr>');};
I have to add up the service charge(10%) plus VAT(8%) to a service, and I'm not sure the right way to increase a number by percentages.
For example: The service costs $1000 and I need to add to it 10% plus 8%. I'm struggling with three different ways to achieve that. Which way is the right one?
var service_charge = 10; // percent
var vat = 8; // percent
var price = 1000;
// OPTION 1
var tmp1 = price * (service_charge / 100);
var tmp2 = price * (vat / 100);
var total_1 = price + tmp1 + tmp2;
// OPTION 2
var tmp3 = price * (service_charge / 100);
var sub_total = price + tmp3;
var tmp4 = sub_total * (vat / 100);
var total_2 = sub_total + tmp4;
// OPTION 3
var tmp5 = price * ((service_charge + vat) / 100);
var total_3 = price + tmp5;
console.log(total_1);
console.log(total_2);
console.log(total_3);
https://jsbin.com/povama/edit?js,console
I think "option 2" is the right one, but I really want to be sure.
If VAT is to be applied after service charge, option 2 is the good one. If you want to summarize it in one single line it would be something like this:
var total = (price*(1+(service_charge/100)))*(1+(vat/100));
I'm basically using functions and if else if statements to build an electricity reading calculator.
The units given is 1236 which is a parameter of the function called elecReading. This will be used as the amount of units used and it will calculate the amount that must be paid.
However, the first 0-500 units are billed at $1 per unit. The next 500-1000 units are billed at $1.10 a unit, and over 1000 units are billed at $3.20 a unit. For example, if I used 1000 units, my bill would be $1050.
I'm unsure how I can get this working without breaking down 1236 into singular numbers manually. How can I write a calculator like this with JavaScript?
Obviously I'm not asking for the complete answer, but a push in the right direction would be very helpful at this stage!
Thanks for the help in advance
The static version would be something like:
var UNIT_PRICE_1001_OVER = 3.20;
var UNIT_PRICE_501_1000 = 1.10;
var UNIT_PRICE_UNDER_500 = 1.00;
function elecReading(units) {
var price = 0;
if (units > 1000) {
price += (units-1000) * UNIT_PRICE_1001_OVER;
units = 1000;
}
if (units > 500) {
price += (units - 500) * UNIT_PRICE_501_1000;
units = 500;
}
price += units * UNIT_PRICE_UNDER_500;
return price;
}
This is assuming the unit price ranges are 1-500, 501-1000, 1001-Inf. Obviously this can be done more generally / with less hardcoding, using a list of objects representing a price range + price per unit in said range.
Try following function. Assuming peak rates are from units 1000+, medium rates from 501-1000, and offpeak rates from 0-500.
You could change the variables names as per your requirements/understanding.
EDITED:
While loop is added to keep reducing total units until they are greater than 1000
function elecReading(units){
var totalUnits=units;
var offPeakRate=1;
var mediumRate=1.10;
var peakRate=3.20;
var totalCharges=0;
if(totalUnits>1000){
PeakUnits = totalUnits-1000;
totalCharges = totalCharges + (PeakUnits * peakRate);
totalUnits = 1000;
}
if(totalUnits > 500){
totalUnits = totalUnits-500;
totalCharges = totalCharges + (totalUnits * mediumRate);
}
totalCharges = totalCharges + (totalUnits * offPeakRate);
return totalCharges;
}
console.log(elecReading(2000));
I've got a simple table that allows users to enter 2 numbers, and then a script then calculates the annual average and gets the totals for all rows that have the same option in the select menu.
I've setup a sample JSFiddle:
http://jsfiddle.net/fmdataweb/73Jzc/1/
that shows how this works. I've just noticed that at times I get a strange rounding error (I want it to round to one decimal place). For example if you select "moderate" and then enter 5 and 4 for an average of 0.4, then click the button to create a new row and select "moderate" again then enter 3 and 40 for an average of 2.3 you'll notice the total for the moderate is "2.6999999999999997" when it should be 2.7.
If you enter other numbers it's fine so far in my testing but for some reason these combinations don't get rounded for the totals and I'm not sure why. Appreciate if anyone can point out the error in my script. Here's the script that does the averages and totals:
$('#nextYear')
.on('change', 'select', calc)
.on('keyup', 'input', calc);
function calc(){
$('#nextYear tr:has(.risk)').each(function(i,v){
var $cel = $(v.cells);
var $risk = $cel.eq(1).find('option:selected').val();
var $numb = $cel.eq(2).find('input').val();
var $weeks = $cel.eq(3).find('input').val();
var $avg = ($numb * $weeks) / 52;
var $avgRounded = Math.round( $avg * 10 ) / 10;
$cel.eq(4).find('input').val($avgRounded);
});
var tot = {};
$('#nextYear tr:has(.risk) option:selected')
.map(function(i){
var el = $(this).val();
var qty = parseFloat($('#nextYear tr:has(.risk)').eq(i).find('td:last').prev().find('input').val());
if (!tot.hasOwnProperty(el)) {
tot[el] = 0;
}
tot[el] += qty
return tot;
}).get();
// console.log(tot);
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
}
You problem is here:
$('#textfield6').val(tot.moderate);
$('#textfield7').val( tot.high );
You must round them like you did with
var $avgRounded = Math.round( $avg * 10 ) / 10;
or using .toFixed(1)
Edit:
Then, the code is:
$('#textfield6').val(tot.moderate.toFixed(1));
$('#textfield7').val(tot.high.toFixed(1));
You can see it here: http://jsfiddle.net/73Jzc/2/
Try $avg.toFixed(1); instead of Math.round( $avg * 10 ) / 10;