#javascript #html
#javascript #HTML
Вопрос:
В качестве учебного упражнения, а также для создания простого, но полезного небольшого инструмента (для меня), я пытаюсь создать веб-форму, которая будет принимать данные о ценах и количестве для нескольких товаров, а затем выдавать «стоимость за единицу» (цена, деленная на количество товара).). Затем, основываясь на этой информации, я хочу, чтобы дальнейшие вычисления предоставили окончательную стоимость, основанную на итоговых затратах для нескольких удельных затрат на эти товары. У меня есть этот простой маленький инструмент, встроенный в электронную таблицу Excel, но я хочу, чтобы он также был в веб-формате.
Я увлекаюсь стрельбой как хобби, и я перезаряжаю свои боеприпасы. Этот инструмент берет оптовую цену / количество для четырех предметов; пули, порох, капсюли и латунные гильзы, выдает стоимость за единицу, а затем сообщает мне стоимость патронов (первая итерация самая дорогая, поскольку включены затраты на новые латунные гильзы), затем последующие загрузки (выбираемое количество) рассчитывается с использованием только стоимости пули, пороха и праймера, поскольку латунь можно перезаряжать несколько раз.
У меня есть начальный запуск с html, отображающего две строки пользовательского ввода, первая строка: маркер, цена, количество, единица измерения. Вторая строка — порошок, цена, количество, единица измерения. Ввод формы форматируется с использованием css grid.
У меня есть скрипт, который работает для выполнения вычислений для первой строки для маркера, но я не знаю, как заставить его повторить, а затем вычислить и вывести данные powder. Я прочитал множество сайтов, касающихся вычислений форм, и большинство, если это прошло прямо у меня над головой. Некоторая помощь в этом была бы признательна.
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06 bprice)/bquantity;
return bcost.toPrecision(2);
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
return false;
};
}
}());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<title>Unit Cost Calculator</title>
</head>
<body>
<div class="contain">
<div class="wrapper">
<div class="form">
<h2>Load Cost Calculator</h3>
<form id="unitCost" action="">
<p>
<label for="bullet">Bullet </label>
<input id="bullet" name="bullet" type="text" />
</p>
<p>
<label for="bprice">Price </label>
<input id="bprice" name="bprice" type="number" step="0.01" />
</p>
<p>
<label for="bquantity">Quantity </label>
<input id="bquantity" name="bquantity" type="number" />
</p>
<p>
<label for="bunit">Unit Cost </label>
<input id="bunit" name="bunit" type="number" step="0.01" />
</p>
<p>
<label for="powder">Powder </label>
<input id="powder" name="powder" type="text" />
</p>
<p>
<label for="pprice">Price </label>
<input id="pprice" name="pprice" type="number" step="0.01" />
</p>
<p>
<label for="pquantity">Quantity </label>
<input id="pquantity" name="pquantity" type="number" />
</p>
<p>
<label for="punit">Unit Cost </label>
<input id="punit" name="punit" type="number" step="0.01" />
</p>
<p>
<label for="subm"></label>
<input type="submit" value="Calculate Per Unit Cost" />
</p>
<p>
<label for="rest"></label>
<input type="reset" value="Reset" />
</p>
</form>
</div>
</div>
</div>
Ok, the suggestion by Ayaz does work, sort of. I swear I tried that before and it did not. I even still have the old copy where I tried it, I just went back and it doesn’t work, but for some reason editing the current working copy, with the exact same code, it works. Sigh, anyway…I’ve also figured out the code to get and calculate the powder data and it too works.
The formula for the powder unit cost is different than for bullets. Bullets are sold in quantity counts, 50, 100, etc. Powder is sold by weight, typically in 1lb or 8lb containers. However, for calculating per cartridge loading costs there is a second weight unit used, «grains.» There are 7000 grains to 1lb. So, the formula I am trying to use for powder is
(pprice*0.06 pprice)/(pquantity*7000)
The 0.06 is there to add in the cost of sales tax. Quantity is entered by the user in pounds, the formula converts it to grains, or is supposed to. When I use that formula, I get weird results. When I run the script with a powder price of 29.99, quantity of 1, it gives me an output of 32. Something is obviously not calculating correctly.
So, I changed the formula to
(pprice*0.06 pprice)/pquantity
and instead of entering 1 for the quantity, I can put in the total grains instead of pounds (7000 for 1lb of powder or 56000 for 8lbs), which is fine since it will always be one or the other.
Затем я столкнулся с проблемой точности результата. Вывод был только с точностью до 4 знаков после запятой в powder. Мне нужен был этот вывод, чтобы перейти как можно дальше. Поскольку одна крупинка пороха невероятно мала с точки зрения цены, это кажется несущественным, но будет важно позже при расчете цен на картридж и особенно при расчете количества патронов, например, 20 патронов на «коробку». То же самое верно и для праймеров, поскольку они поставляются в коробках по 1000 штук. Затем я попытался добавить:
return pcost.toPrecision(8);
но это ничего не изменило. Итак, после добавления дополнительных полей для праймеров и латуни и игры я обнаружил, что строка кода
return bcost,toPrecision(2);
был виновником. Удаляя часть «.toPrecision», все возвращается к тому, сколько десятичных знаков оно фактически вычисляет.
Переходим к следующему шагу, теперь, чтобы сделать больше математики и вывести стоимость одного полного раунда, добавив стоимость единицы для каждого элемента вместе (а затем округлите его до 2 знаков после запятой). Собираюсь попробовать поработать над этим сейчас…У меня, вероятно, будет больше вопросов по этому поводу..
Вот текущий рабочий код:
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06 bprice)/bquantity;
pprice = parseFloat(pprice);
pquantity = parseFloat(pquantity);
pcost = (pprice*0.06 pprice)/pquantity;
prprice = parseFloat(prprice);
prquantity = parseFloat(prquantity);
prcost = (prprice*0.06 prprice)/prquantity;
brprice = parseFloat(brprice);
brquantity = parseFloat(brquantity);
brcost = (brprice*0.06 brprice)/brquantity;
return bcost;
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
this.punit.value = calculateUnitCost(this.pprice.value, this.pquantity.value);
this.prunit.value = calculateUnitCost(this.prprice.value, this.prquantity.value);
this.brunit.value = calculateUnitCost(this.brprice.value, this.brquantity.value);
return false;
};
}
}());
Комментарии:
1. Вы хотите рассчитать стоимость единицы пули и пороха с помощью кнопки «Рассчитать стоимость за единицу» и заполнить текстовое поле «Стоимость за единицу» для пули и пороха?
2. Да, именно так. Я хочу нажать кнопку «Рассчитать» один раз и выполнить все вычисления для каждого элемента с ответом, заполненным в поле «Единица измерения» для каждого элемента.
Ответ №1:
Используйте приведенный ниже код, если формула расчета на единицу одинакова для Powder.
(function () {
function calculateUnitCost(bprice, bquantity) {
bprice = parseFloat(bprice);
bquantity = parseFloat(bquantity);
bcost = (bprice*0.06 bprice)/bquantity;
return bcost.toPrecision(2);
}
var unitCost = document.getElementById("unitCost");
if (unitCost) {
unitCost.onsubmit = function () {
this.bunit.value = calculateUnitCost(this.bprice.value, this.bquantity.value);
this.punit.value = calculateUnitCost(this.pprice.value, this.pquantity.value);
return false;
};
}
}());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="style.css">
<title>Unit Cost Calculator</title>
</head>
<body>
<div class="contain">
<div class="wrapper">
<div class="form">
<h2>Load Cost Calculator</h3>
<form id="unitCost" action="">
<p>
<label for="bullet">Bullet </label>
<input id="bullet" name="bullet" type="text" />
</p>
<p>
<label for="bprice">Price </label>
<input id="bprice" name="bprice" type="number" step="0.01" />
</p>
<p>
<label for="bquantity">Quantity </label>
<input id="bquantity" name="bquantity" type="number" />
</p>
<p>
<label for="bunit">Unit Cost </label>
<input id="bunit" name="bunit" type="number" step="0.01" />
</p>
<p>
<label for="powder">Powder </label>
<input id="powder" name="powder" type="text" />
</p>
<p>
<label for="pprice">Price </label>
<input id="pprice" name="pprice" type="number" step="0.01" />
</p>
<p>
<label for="pquantity">Quantity </label>
<input id="pquantity" name="pquantity" type="number" />
</p>
<p>
<label for="punit">Unit Cost </label>
<input id="punit" name="punit" type="number" step="0.01" />
</p>
<p>
<label for="subm"></label>
<input type="submit" value="Calculate Per Unit Cost" />
</p>
<p>
<label for="rest"></label>
<input type="reset" value="Reset" />
</p>
</form>
</div>
</div>
</div>
Комментарии:
1. Я действительно пробовал это, и это не работает. Однако расчет для элемента powder — это тоже другая формула.
2. Не обращайте внимания на предыдущий комментарий, он также работает с дополнительными дополнениями. Не сработало, когда я попробовал это на предыдущей итерации… странно.
3. Да, вы можете написать другую функцию, которая должна реализовывать другую логику, и вызвать ее для вычисления Powder ..