Jquery: calculate volume - javascript

Took the base of a code from one user and modified a bit. Basically it does what i need - calculates the sum from three values (first two are in meters, third in centemeters). but i would like it to be more simpler. I dont't need "select options" in thickness field - it must be calculated in centemeters!.
And second request - the amount must be in m3!
html:
<table>
<tbody>
<tr>
<td>Width (m)</td>
<td>
<input type="text" id="width" />
</td>
</tr>
<tr>
<td>Length (m)</td>
<td>
<input type="text" id="length" />
</td>
</tr>
<tr>
<td>Thickness (cm)</td>
<td>
<input type="text" id="thickness" />
</td>
<td>
<select id="sel">
<option>centemeter</option>
<option>meter</option>
<option>melemeter</option>
</select>
</td>
</tr>
<tr>
<td>Total (m<sup>3</sup>)</td>
<td id="answer"></td>
</tr>
</tbody>
</table>
javascript:
$("#width ,#length ,#thickness, #sel").on('change keyup keydown', function() {
var width = $("#width").val();
var length = $("#length").val();
var thickness = $("#thickness").val();
var result = width * length * thickness;
var select_val = $("#sel").val();
if (select_val == "centemeter") {
$("#answer").text(result).append(" cm<sup>3</sup>");;
} else if (select_val == "meter") {
result = result / 100;
$("#answer").text(result).append(" m<sup>3</sup>");;
} else if (select_val == "melemeter") {
result = result * 10;
$("#answer").text(result).append(" mm<sup>3</sup>");
}
});
jsfiddle
update: i thought this will be an easy task: calculate amount of three numbers - something like var result = width * length * thickness; only thickness is 1/100 of width and length...

below solution to my answer. wasn't that complicated, is it?
$("#width ,#length ,#thickness").on('change keyup keydown', function () {
var width = $("#width").val();
var length = $("#length").val();
var thickness = $("#thickness").val();
var result = width * length * thickness;
result = result/100;
$("#answer").text(result).append(" m<sup>3</sup>");;
});
jsfiddle

Related

Exclude certain rows while calculating the minimum value

I have the following table and I need to find the minimum value in that column.
In this case the value is 20.
However, I need to exclude the last 2 part names and use the rest of the values in the cell to calculate the minimum. In that case the minimum value should be 100.
Here is the code i have for calculating the minimum:
function getMin() {
var maximum = 0;
jQuery(".used").each(function() {
$used= jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
maximum = (value > maximum) ? value : maximum;
});
var min = maximum;
jQuery(".used").each(function() {
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
min = (value < min) ? value : min;
});
jQuery(".minimum").val(min);
}
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="getMin();" readonly>cycles</div>
I couldn't find a way to exclude the last 2 values here. The number of rows can also differ and is not fixed so I need to exclude it based on those 2 string values. Any help is appreciated!! Thank you in advance!
Here is a quick and dirty solution. Loop through the parent object of each row, and ignore the value of used if the label (text) is one of those strings.
I also updated the minimum function to use the math.min on an array of values.
function getMin() {
let vals = [];
$(".row").each(function() {
if ($(this).find("label").html() != "Ignore") {
$used = $(this).find(".used").val();
var usedValue = $used.replace(/,/g, "");
vals.push(parseFloat(usedValue));
}
});
let min = Math.min(...vals);
$(".minimum").val(min);
}
getMin();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<label>Ignore</label>
<input type="text" class="used" value=41>
</div>
<div class="row">
<label>Keep</label>
<input type="text" class="used" value=222>
</div>
<div class="row">
<label>Keep</label>
<input type="text" class="used" value=200>
</div>
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="" readonly>cycles</div>
I would mark these different rows in HTML somehow, let's say with excluded class. Hardcoding the labels in JavaScript asks for trouble.
Here's an example, using excluded class for these two last <tr>:
const min = Math.min(...$(':not(.excluded) .used').map(function () {
return Number($(this).val());
}).get());
You could do it like this: Exclude in your each() function every <tr> that has a first column that contains any of the 2 strings you want to exclude:
function getMin() {
var maximum = 0;
jQuery(".used").each(function() {
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
maximum = (value > maximum) ? value : maximum;
});
var min = maximum;
jQuery("tr").each(function() {
var check = jQuery(this).find("td:nth-child(1)").text();
if (!check.includes("Fan Blade") && !check.includes("Annulus Filler"))
{
$used = jQuery(this).val();
var usedValue = $used.replace(/,/g, "");
value = parseFloat(usedValue);
min = (value < min) ? value : min;
}
});
jQuery(".minimum").val(min);
}
getMin();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td></td>
<td></td>
<td><input class="used" value="100" /></td>
</tr>
<tr>
<td>Fan Blade (26 off)</td>
<td></td>
<td><input class="used" value="50" /></td>
</tr>
<tr>
<td>Annulus Filler (26 off)</td>
<td></td>
<td><input class="used" value="50" /></td>
</tr>
</table>
<div><input type="text" class="minimum" name="minimum" id="minimum" value="" size="5" onchange="getMin();" readonly>cycles</div>

proper arithmetic operation for two function in javascript

I want to have a addition of two sum of function to get a overall total. but in return they are just combine in one or the results return NAN.
//function for display
function update_price() {
var row = $(this).parents('.item-row');
var price = row.find('.cost').val().replace("₱" ,"") * row.find('.qty').val();
price = roundNumber(price,2);
isNaN(price) ? row.find('.price').html("N/A") : row.find('.price').html("₱" +price);
update_total();
update_balance();
update_ftotal();
}
function update_total() {
var total = 0;
$('.price').each(function(i){
price = $(this).html().replace("₱" ,"");
if (!isNaN(price)) total += Number(price);
});
total = roundNumber(total,2);
$('#subtotal').html("₱" +total);
//$('#total').html("₱"+total);
}
function update_balance() {
var tax = $("#subtotal").html().replace("₱" ,"") * (0.12);
tax = roundNumber(tax,2);
$('.tax').html("₱" +tax);
}
function update_ftotal() {
var sub , ax = 0;
var sub = $("#subtotal").html();
var ax = $('.tax').html();
var due = sub + ax
// due = roundNumber(due,2);
$('.due').html(due);
}
here's the frontend where i use the class and id in the function
<tr>
<td colspan="3" class="blank"> </td>
<td colspan="3" class="total-line">Subtotal:</td>
<td class="total-value"><div id="subtotal" name="subtotal"></div></td>
</tr>
<tr>
<td colspan="3" class="blank"> </td>
<td colspan="3" class="total-line">12% Tax:</td>
<td class="total-value"><div class="tax" id="tax"></div></td>
</tr>
<tr>
<td colspan="3" class="blank"> </td> <!-- add tax result to the subtotal to get final total -->
<td colspan="3" class="total-line balance">Total:</td>
<td class="total-value balance"><div class="due" id="due"></div></td>
</tr>
the result
enter image description here
sub and ax are strings, thus the plus operator concatenates them.
Try this:
var due = parseFloat(sub) + parseFloat(ax);
The answer.
function update_ftotal() {
var sub , ax = 0;
var sub = $(".subtotal").html();
var ax = $(".tax").html();
var num1 = Number(sub);
var num2 = Number(ax);
var due = num1 + num2;
due = roundNumber(due,2);
$('.due').html(due);
}

percentages when converting sterling to euro

Hi I am trying to convert Sterling to Euros. But I can't seem to get the percentages correct. I have tried it several ways without luck. The idea is to get 1% of the sterling price then multiply it by the conversion rate and add it to the sterling price to make the euro total, and then do the same with vat.
Hope someone can help, thanks!
Here is my code.
var input = document.querySelectorAll('input');
var conversionRate = input[0];
var sterling = input[1];
var vat = input[2];
var euro = input[3];
init();
function init() {
calculateKeyUp();
}
function calculateKeyUp() {
for (var i = 0; i < input.length; i++) {
input[i].addEventListener("keyup", function() {
//var totalLessVat = (sterling.value) + (conversionRate.value * (sterling.value / 100));
var sterling1Per = sterling.value / 100;
var convert = sterling1Per * conversionRate.value;
var totalLessVat = convert + sterling.value;
//var total = (totalLessVat) + (vat.value * (totalLessVat / 100));
var euro1Per = totalLessVat / 100;
var addVat = euro1Per * vat.value;
var total = addVat + totalLessVat;
euro.value = Math.floor(total);
});
}
}
<div id="calculator-form">
<table>
<tr>
<td>Conversion Rate: </td>
<td><input type="number" id="conversionRate"> %</td>
</tr>
<tr>
<td>Sterling Price: </td>
<td><input type="number" id="sterling"> £</td>
</tr>
<tr>
<td>Vat: </td>
<td><input type="number" id="vat"> %</td>
</tr>
<tr>
<td>Euro Price is </td>
<td><input type="number" id="euro" disabled> €</td>
</tr>
</table>
</div>
The .value of an input is going to be a String, so you will need to parse the number out of each input you are working with. If it's an int you can use:
var sterling1Per = parseInt(sterling.value, 10) / 100;
If it's a float, you can use:
var sterling1Per = parseFloat(sterling.value) / 100;
Anywhere that you use an input .value that needs to be a number needs to be parsed accordingly

Find element based on highest value of inputbox in same table row

I have a table with three columns.
Column 1 has inputboxes.
Column 2 contains a "conversion" number which multiplies it's value with the value in the inputbox (column 1)
and the result is outputted in column 3.
It would look something like this:
5 2 10
1 1 1
2 1 2
3 2 6
How can I get column 3's value based on the highest inputbox value in the same row?
My code so far:
HTML
<table border="1px">
<tbody id="mbtbody">
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">5</td>
<td class="totals"></td>
</tr>
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">1</td>
<td class="totals"></td></tr>
<tr>
<td><input class="weightinputclass" type="number" value="0"></td>
<td class="conversionclass">1</td>
<td class="totals"></td>
</tr>
</tbody>
</table>
jQuery
$("#btn").click(function(){
var rows = $("#mbtbody").children("tr");
var total = 0;
rows.each(function(idx, row) {
var $row = $(row);
total += parseInt($row.find('input.weightinputclass').val());
$("#totalweight").html(total);
});
})
$(document).on('input', '.weightinputclass', function () {
var $row = $(this).closest("tr");
var weight = $row.find("input.weightinputclass").val();
var conversion= $row.find(".conversionclass").html();
$row.find(".totals").text(weight*conversion);
})
Fiddle: https://jsfiddle.net/rdawkins/9fyLqfgr/16/
Here is a solution I found:
Javascript
$("#btn").click(function(){
var rows = $("#mbtbody").children("tr");
var total = 0;
rows.each(function(idx, row) {
var $row = $(row);
total += parseInt($row.find('input.weightinputclass').val());
$("#totalweight").html(total);
});
var currentMax = 0;
var currentMaxEl;
$('.weightinputclass').each(function (idx, element) {
var elVal = parseInt($(element).val());
if(elVal > currentMax) {
currentMax = elVal;
currentMaxEl = $(element);
}
});
var maxWeight = currentMaxEl.parent().parent().children('.totals').first().html();
$('#highestinput').html(2000 - maxWeight);
})
$(document).on('input', '.weightinputclass', function () {
var $row = $(this).closest("tr");
var weight = $row.find("input.weightinputclass").val();
var conversion= $row.find(".conversionclass").html();
$row.find(".totals").text(weight*conversion);
});
Fiddle
https://jsfiddle.net/9v6j8qub/2/

Using if and else if functions with select inputs (converting results based on km and miles)

I have been trying to build a race predictor calculator based off of Peter Riegel's formula for a couple of days now and have only managed to get it working when the original and future distances are set the same (See below).
However I would like for the user to be able to select kilometres or miles using 'select' and 'options' in the form for both the original and future distance. I have played around with else and else if statements in the script but have completely failed at this. I would greatly appreciate it if someone could help me crack this. (I have put the select and options in already so it is just the scripting that I need help with).
I am completely self taught so I apologise if the code below is a complete mess or incorrect. Thank you! James
function predictorCalc() //Predicting future race results
{
var d1 = document.predictor.d1.value;
var t1 = document.predictor.time1hr.value * 60 * 60 + document.predictor.time1min.value * 60 + document.predictor.time1sec.value * 1;
var deg = document.predictor.deg.value;
var d2 = document.predictor.d2.value;
//NEED TO INPUT IF & ELSE IF STATEMENTS HERE TO MANIPULATE THE RESULT DEPENDING ON WHETHER THE DISTANCE SELECTED IN D1 or D2 is KM OR MILES//
t2 = t1 * (Math.pow((d2 / d1), deg)); //predicted time in seconds (Equation T2=T1*(D2/D1)1.06)
phr = Math.floor(t2/3600); //total hrs
pmin = Math.floor((t2 - (phr*(3600)))/60); //total mins
psec = Math.floor(t2 - (phr*(3600))-(pmin*60)); //total secs
document.predictor.time2hr.value = round(phr,0);
document.predictor.time2min.value = round(pmin,0);
document.predictor.time2sec.value = round(psec,0);
}
function round(x) {
return Math.round(x*100)/100;
}
<form name="predictor">
<table>
<tbody>
<tr>
<td>D1 (Original distance)</td>
<td><input type="text" name="d1" size="3">km</td>
<td>
<select size="1" name="d1units">
<option selected="" value="k">Kilometers</option>
<option value="m">Miles</option>
</select>
</td>
</tr>
<tr>
<td>T1 (original time)</td>
<td><input name="time1hr" size="3" maxlength="2" type="text">hr</td>
<td><input type="text" name="time1min" size="3">min</td>
<td><input type="text" name="time1sec" size="3">sec</td>
</tr>
<tr>
<td>D2 (Future distance competing in)</td>
<td><input type="text" name="d2" size="3">km</td>
<td>
<select size="1" name="d2units">
<option selected="" value="k">Kilometers</option>
<option value="m">Miles</option>
</select>
</td>
</tr>
<tr>
<td>Performance Degradation</td>
<td colspan="3"><input name="deg" size="2" maxlength="4" type="text" value="1.06">(6% or 1.06 as standard)</td>
</tr>
<tr>
<td><input onclick="predictorCalc()" value="Calculate" type="button"></td>
</tr>
<tr>
<td>T2 (Predicted future time)</td>
<td><input name="time2hr" size="3" maxlength="2" type="text">hr</td>
<td><input type="text" name="time2min" size="3">min</td>
<td><input type="text" name="time2sec" size="3">sec</td>
</tr>
</tbody>
</table>
</form>
function predictorCalc() //Predicting future race results
{
const kmPerMile=1.60934;
var d1u = document.predictor.d1units;
var d1units = d1u.options[d1u.selectedIndex].value;
var d1 = d1units=='k'?document.predictor.d1.value:document.predictor.d1.value*kmPerMile;
var d2u = document.predictor.d2units;
var d2units = d2u.options[d2u.selectedIndex].value;
var d2 = d2units=='k'?document.predictor.d2.value:document.predictor.d2.value*kmPerMile;
var t1 = document.predictor.time1hr.value * 60 * 60 + document.predictor.time1min.value * 60 + document.predictor.time1sec.value * 1;
var deg = document.predictor.deg.value;
//NEED TO INPUT IF & ELSE IF STATEMENTS HERE TO MANIPULATE THE RESULT DEPENDING ON WHETHER THE DISTANCE SELECTED IN D1 or D2 is KM OR MILES//
t2 = t1 * (Math.pow((d2 / d1), deg)); //predicted time in seconds (Equation T2=T1*(D2/D1)1.06)
phr = Math.floor(t2/3600); //total hrs
pmin = Math.floor((t2 - (phr*(3600)))/60); //total mins
psec = Math.floor(t2 - (phr*(3600))-(pmin*60)); //total secs
document.predictor.time2hr.value = round(phr,0);
document.predictor.time2min.value = round(pmin,0);
document.predictor.time2sec.value = round(psec,0);
}

Categories

Resources