Calculate the volume - javascript

I would like to create similar calculator like here. It calculates the volume of a mulch. Visitor inserts three numbers: width, length and height (thickness) and it tells how much it has to buy.
html:
<form method="post" accept-charset="UTF-8">
<div class="form_area">
<div class="form_fields">
<div class="form_field ">
<label class="form_field_label">Width (m)</label>
<input type="text" value="" name="laius" id="laius" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Length (m)</label>
<input type="text" value="" name="pikkus" id="pikkus" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Thickness (cm)</label>
<input type="text" value="" name="paksus" id="paksus" rel="calc" class="form_field_textfield form_field_size_medium">
</div>
<div class="form_field ">
<label class="form_field_label">Total (m<sup>3</sup>)</label>
<input type="text" value="" readonly name="kokku" id="kokku" class="form_field_textfield form_field_size_small">
</div>
</div>
<div class="form_submit">
<input type="submit" value="Arvuta" id="calc_submit" name="commit">
</div>
</div>
</form>
javascript:
! function($) {
$(function() {
$("[rel='calc']").arvutus();
});
$.fn.arvutus = function() {
var inputs = $(this);
var kokku = $("#kokku:first");
inputs.bind("change keyup", function() {
var obj = $(this);
if (obj.val() !== "") {
parseFloat(obj.val()).toFixed(2);
};
arvuta();
});
$("#calc_submit").bind("click", function(e) {
e.preventDefault();
arvuta();
});
function arvuta() {
var width = inputs.filter("#laius").val();
width = width.toString();
width = width.replace(",", ".");
var lenght = inputs.filter("#pikkus").val();
lenght = lenght.toString();
lenght = lenght.replace(",", ".");
var thickness = inputs.filter("#paksus").val();
thickness = thickness.toString();
thickness = thickness.replace(",", ".");
thickness = thickness / 100;
var sum = width * lenght * thickness
sum = sum.toFixed(2);
kokku.val(sum + " m3 multši.");
};
};
}(window.jQuery);
I inserted html and javascript into jsfiddle, but mine doesn't work. Probably i miss something very obvious. some more javascript?
update: a little while ago, somebody provided a working code, but moderator removed it so quickly i couldn't copy it... :(

The code parseFloat(obj.val()).toFixed(2) returns a value, but you're not doing anything with it. Should it be stored somewhere so you can use it in calculating the volume?

Related

How do I make this conversion function work in both directions?

I'm new in JS and I have trouble to finish a converter only with inputs, I explain the problem !
We have two input, Meters and Feet. when I transmit a number to Feet I have the result in Meters. And I Want to do the same think with Meters . and vice versa
let metresEl = document.getElementById('inputMetres');
function LengthConverter(valNum) {
metresEl.value = valNum/3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value)" onchange="LengthConverter(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres">
</div>
</div>
You can add another parameter in the LengthConvertor function which will say the input unit (meter or feet) and convert it accordingly inside the function using if.
function LengthConverter(valNum, inputUnit) {
if(inputUnit === 'feet')
metresEl.value = valNum/3.2808;
if(inputUnit === 'meter')
feetsEL.value = valNum * 3.2808;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="LengthConverter(this.value,"feet")" onchange="LengthConverter(this.value,"feet")" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="LengthConverter(this.value,"meter")" onchange="LengthConverter(this.value,"meter")" >
</div>
</div>
Added inverse conversion:
let metresEl = document.getElementById('inputMetres');
let feetEl = document.getElementById('inputFeet');
function FeetToMetres(valNum) {
metresEl.value = valNum/3.2808;
}
function MetresToFeet(valNum) {
feetEl.value = 3.2808*valNum;
}
<div class="container">
<div class="form-group">
<label>Feet</label>
<input type="number" id="inputFeet" placeholder="Feet" oninput="FeetToMetres(this.value)" onchange="FeetToMetres(this.value)" >
</div>
<div class="form-group">
<label>Metres</label>
<input type="number" id="inputMetres" placeholder="Metres" oninput="MetresToFeet(this.value)" onchange="MetresToFeet(this.value)">
</div>
</div>
You can add a element.addEvenetListener to each input, and when it chances you get it's value, convert, and put in on the right input.
let metresEl = document.getElementById('inputMetres');
let feetsEl = document.getElementById('inputFeets');
metresEl.addEventListener('change', yourCode);
feetsEl.addEventListener('change', yourCode);
For exemple, if metres input changes, you convert to feets and add to feets input.

Launching a new window and filling form values using Javascript

I have been learning JavaScript and i am attempting to launch a new window on click after a user has placed info into a form fields and then placing that info into form fields in the newly launched window. I have read many posts and methods in Stackoverflow however i cant seem to get it to work properly.
Starting page HTML:
<form id="memCat" methed="get" class="member_catalogue">
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002_thumb.jpg" name="Red Bowl"></button>
<div class="cat_block">
<label class="cat_label" for="cat_name">Product Name:</label>
<input class="cat_input" type="text" id="catID" value="bepot002" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_description">Product Description:</label>
<input class="cat_input" type="text" id="catDesc" value="Ocre Red Pot" readonly>
</div>
<div class="cat_block">
<label class="cat_label" for="cat_price">Per unit price:$</label>
<input class="cat_input" type="number" id="catVal" value="10" readonly>
</div>
</form>
New page HTML:
<form id="memOrder" method="post">
<div>
<label for="pname">Product Name:</label>
<input type="text" id="orderID" readonly>
</div>
<div>
<label for="pdescription">Product Description:</label>
<input type="text" id="orderDesc" readonly>
</div>
<div>
<label for="quantity">Quantity ordered:</label>
<input type="number" class="quantOrder" id="orderOrder" value="1" min="1" max="10">
</div>
<div>
<label for="ind_price">Per unit price: $</label>
<input type="number" class="quantCount" id="orderVal" readonly>
</div>
<div>
<label for="tot_price">Total Price: $</label>
<input type="number" class="quantCount" id="orderTotal" readonly>
</div>
<div>
<button type="reset">Clear Order</button>
<button type="submit" id="orderCalc">Calculate Total</button>
<button type="submit" id="orderPlace">Place Order</button>
</div>
</form>
Script i have to date:
function openMemberOrder() {
document.getElementById("orderID").value = document.getElementById("catID").document.getElementsByTagName("value");
document.getElementById("orderDesc").value = document.getElementById("catDesc").document.getElementsByTagName("value");
document.getElementById("orderVal").value = document.getElementById("catVal").document.getElementsByTagName("value");
memberOrderWindow = window.open('Member_Orders/members_order.html','_blank','width=1000,height=1000');
};
script and other meta tags in head are correct as other code is working correctly.
So after much trial and error i have had success with this:
On the submission page:
1. I created a button on the page that will capture the input form data
2. i created the localstorage function in JS
3. I then placed the script tag at the bottom of the page before the closing body tag
HTML
<button type="submit" class="prodBtn" id="catOrder" onclick="openMemberOrder()"><img class="prodImg" src="../../../Images/bcpot002/bcpot002_thumb.jpg" name="Red Bowl"></button>
Javascript
var catID = document.getElementById("catID").value;
var catDesc = document.getElementById("catDesc").value;
var catVal = document.getElementById("catVal").value;
function openMemberOrder() {
var memberOrderWindow;
localStorage.setItem("catID", document.getElementById("catID").value);
localStorage.setItem("catDesc", document.getElementById("catDesc").value);
localStorage.setItem("catVal", document.getElementById("catVal").value);
memberOrderWindow = window.open('Member_Orders/members_order.html', '_blank', 'width=1240px,height=1050px,toolbar=no,scrollbars=no,resizable=no');
} ;
Script Tag
<script type="text/javascript" src="../../../JS/catOrder.js"></script>
I then created the new page with the following javascript in the header loading both an image grid as well as input element values:
var urlArray = [];
var urlStart = '<img src=\'../../../../Images/';
var urlMid = '_r';
var urlEnd = '.jpg\'>';
var ID = localStorage.getItem('catID');
for (var rowN=1; rowN<5; rowN++) {
for (var colN = 1; colN < 6; colN++){
urlArray.push(urlStart + ID + '/' + ID + urlMid + rowN + '_c' + colN + urlEnd)
}
}
window.onload = function urlLoad(){
document.getElementById('gridContainer').innerHTML = urlArray;
document.getElementById('orderID').setAttribute('value', localStorage.getItem('catID'));
document.getElementById('orderDesc').setAttribute('value', localStorage.getItem('catDesc'));
document.getElementById('orderVal').setAttribute('value', localStorage.getItem('catVal'));
};
I then created 2 buttons to calculate a total based on inputs and clearing values separately, the script for this was placed at the bottom of the page.
function total() {
var Quantity = document.getElementById('orderQuant').value;
var Value = document.getElementById('orderVal').value;
var Total = Quantity * Value;
document.getElementById('orderTotal').value = Total;
}
function clearForm() {
var i = 0;
var j = 0;
document.getElementById('orderQuant').value = i;
document.getElementById('orderTotal').value = j;
}

Add off option value in JS and html

I want to add off option value in my page
For example, you come in my shop page and choose a package, I want to add an option field for the Discount and when you enter a text that is available on s.txt you receive a discount offer.
For example, you enter a StackOverflow code and in s.txt:
stackoverflow--20
Then the price will be reduced by %20 and displayed.
My source code follows.
JavaScript:
$("#payBtn").click(function() {
$("#count").html($("#member").val());
var price = $("#member").val();
price = price * 5;
location.href = 'https://zarinp.al/levicoder/' + price;
});
$("#name").keyup(function() {
$("#payerName").html($("#name").val());
});
$("#channelInput").keyup(function() {
$("#channel").html($("#channelInput").val());
});
$("#discount").keyup(function() {
$("#disdis").html($("#discount").val());
});
$("#member").click(function() {
$("#count").html($("#member").val());
var price = $("#member").val();
price = price * 5;
$("#amount").html(price);
});
Html:
<div class="box shadow_box purchase_cm_box" >
<h4>Order</h4>
<hr>
<input type="text" class="form-control" id="name" placeholder="Your name"><br>
<input type="text" class="form-control" id="channelInput" placeholder="Your Id"><br>
<input type="text" class="form-control" id="discount" placeholder="discount code"><br>
<div class="form-group">
<select class="form-control" id="member">
<option value="9000">9000 Value</option>
<option value="2000">2000 Value</option>
</select>
<br>
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 pull-left" id="leftmenu">
<div class="box shadow_box purchase_cm_box" >
<h4>Factor</h4>
<hr>
Your Name : <label id="payerName">don't entered</label><br>
Your id : <label id="channel"></label><br>
discount code : <label id="disdis"></label><br>
Pay Count
<label id="amount">7,000</label>
$
<br><br>
<button class="getBtn" id="payBtn">Pay</button><br>
<p id="payStatus"></p>
</div>
</div>
I tried not to officially answer this question because I am unsure what LeVi needs. But as a result of our conversation in the comments, I was asked to provide code.
Here's my best guess of what LeVi is asking:
let inputCode = "stackoverflow";
let savedCode = "stackoverflow--20"; // derived from file s.txt
let splitSavedCode = savedCode.split('--'); // this will return ['stackoverflow', '20']
if( inputCode == splitSavedCode[0] ) {
// edited after further discussion in comments
let discountPercentage = splitSavedCode[1] / 100;
let discountAmount = price * discountPercentage;
$('#discount').val(discountAmount);
}

Limit checkbox and calculate between 2 active input fields

I'm trying to calculate the %share which is simply an addition of share1+share2 == 100. However, I want it to work only on the two checked checkboxes.
How do I go about detecting the selected checkbox and apply the function accordingly?
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$("#share1").focusout(function() {
var share1 = $("#share1").val();
var answer = 100 - share1;
$("#share2").val(answer);
});
$("#share2").focusout(function() {
var share2 = $("#share2").val();
var answer = 100 - share2;
$("#share1").val(answer);
});
label {
display: block;
}
.block {
background-color: #eee;
padding: 15px;
margin-bottom: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<h6>You can choose a maximum of 2 users</h6>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share1" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share2" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share3" class="form-control" placeholder="% share" required>
</div>
</div>
<div class="block">
<label class="checkbox"> Add User
<input class="addnominee" type="checkbox" data-toggle="collapse" data-target="#fnominee">
</label>
<div class="form-group">
<input type="number" pattern="[0-9]*" id="share4" class="form-control" placeholder="% share" required>
</div>
</div>
Do you have a specific reason to use focusout?
You could catch the ID's of the two "selected" elements inside your checkbox function. Or to be precise, get id of input that is in the next div inside the clicked checkbox's parent:
var active1, active2;
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
let checked = $('input.addnominee:checked');
active1 = $(checked[0]).parent().next('div').children('input').attr('id');
//Let's assign active2 only if we have multiple selected checkboxes:
if(checked.length > 1) active2 = $(checked[1]).parent().next('div').children('input').attr('id');
});
Here's example with click. To simplify it a bit, I added stepper class into every number input, and we're now detecting click for the class stepper:
$(document).on('click','.stepper',function(){
if($(this).attr('id') == active1){ //Check which one user clicked
if(active2 != undefined){ //Make the math only if we have another active element
var share1 = $('#'+active1).val();
var answer = 100 - share1;
$('#'+active2).val(answer);
}
}else if($(this).attr('id') == active2){
if(active1 != undefined){
var share2 = $('#'+active2).val();
var answer = 100 - share2;
$('#'+active1).val(answer);
}
}
});
Fiddle: https://jsfiddle.net/xpvt214o/677733/
This surely works also with focusout, but you need to remember that clicking stepper wont focus the input, so it wouldn't be very functional.
And with this same idea you could also disable the inputs which are not 'active'.
I hope this helps!
EDIT:
Maybe a bit simplified version with the same idea:
jQuery(document).ready(function($) {
var MAX = 2;
$('input.addnominee').click(function() {
($('input.addnominee:checked').length == MAX) ? $('input.addnominee').not(':checked').attr('disabled',true):$('input.addnominee').not(':checked').attr('disabled',false);
});
$(document).on('click','.stepper',function(){
var checked = $('input.addnominee:checked');
if(checked.length > 1){
var active1 = $(checked[0]).parent().next('div').children('input');
var active2 = $(checked[1]).parent().next('div').children('input');
var share = $(this).val();
var answer = 100 - share;
if($(this).attr('id') == $(active1).attr('id')){
$(active2).val(answer);
}else if($(this).attr('id') == $(active2).attr('id')){
$(active1).val(answer);
}
}
});
});
Fiddle: https://jsfiddle.net/128uzmj3/

Updating same html Element with jQuery when user input changes

I am trying do some calculations that take user input and supply the calculated value for the user to see. The user will supply two values and then the result, ADF, will be returned.
Two problems that I am having: The value is calculated before I have entered the second value (FG); and when either value is changed, the old ADF is not replaced. I understand that is because it keeps applying .append(), but I do not know what I need to use instead. I have provided pictures of what is happening. I have listed my code below.
*Note the round() and ADF() functions are my Javascript functions used for the calculations and I didn't think it relevant to list that code. Let me know if you think it is relevant to see it.
Thanks in advance for your help.
function main() {
$(document).on('change', '#Gravities', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').append('<div class="ADF">'+calc+'%</div>');
});
}
$(document).ready(main);
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
</body>
</html>
enter image description here
enter image description here
$(document).on("input", ".gravity", function() {
var thisval = $(this).val()
var nothisval = $(".gravity").not(this).val()
if (thisval.length > 0 && nothisval.length > 0) {//check if one value is empty
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
//var calc = round(ADF(OG, FG) * 100, 2);
var calc = OG * FG;//change this computation
//$('.ADFbox').append('<div class="ADF">' + calc + '%</div>');
$('.ADFbox').text("ADF:" + calc).change();
} else {
$('.ADFbox').text("ADF: 0");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' class="gravity"name='OG' value ="" /></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' class="gravity" name='FG' value=""/></label></p>
</div>
</form>
<div class='ADFbox'>
<p>ADF:</p>
</div>
</body>
Check of each value then proceed if both value has length more than 0
Note: input has no ending tag just close like <input />
To solve this you could place the .adf div in the HTML on load and then simply update it's text() instead of using append() to create a new copy after each calculation.
Below is a working example. Note that I simplified the calculation as you didn't provide the logic of the round() or ADF() functions. Try this:
function main() {
$(document).on('change', '#Gravities', function() {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
//var calc = round(ADF(OG, FG) * 100, 2);
var calc = OG * FG;
$('.ADFbox .adf').text(calc + '%');
});
}
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Gravities">
<div>
<p>
<label class="originalGravity">
OG:
<input type='text' name='OG' value="">
</label>
</p>
</div>
<div>
<p>
<label class="finalGravity">
FG:
<input type='text' name='FG' value="">
</label>
</p>
</div>
</form>
<div class='ADFbox'>
<p>ADF: <div class="adf"></div></p>
</div>
The problem you are appending html not updating the existing text value.
Just change your code like below:
$(document).on('change', '#Gravities', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
if(OG != "" && FG != ""){
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').find("p").html("ADF:"+ calc + '%');
}
});
function main() {
$(document).on('change', '#Gravities', function () {
if($('input[name=OG]').val()!='' && $('input[name=FG]').val()!=''){
var calc = round(ADF(OG,FG)*100, 2);
$('.ADFbox').html('<div class="ADF">'+calc+'%</div>');
}
});
}
$(document).ready(main);
<body>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
</body>
</html>
You have added on change event. that's why it's getting calculated each time when any one of the fields got updated. I made few changes:
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='number' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='number' name='FG' value=""></input>
</label></p>
</div>
<button type="button" id="fgs">
Find ADF</button>
</button>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>
function main() {
$("#fgs").on('click', function () {
OG = $('input[name=OG]').val();
FG = $('input[name=FG]').val();
var calc = OG*FG;
document.getElementsByClassName("ADFbox")[0].innerHTML= "ADF:"+" " +calc;
});
}
$(document).ready(main);
created working fiddle for you: https://jsfiddle.net/Safoora/hspdgqca/15/
Sorry if I'm not understanding you. As per my understanding you need to calculate only if both inputs field are changed? If it is so, you can do like this:
function main() {
$(document).on('change', '#Gravities input', function () {
OG = $('input[name=OG]');
FG = $('input[name=FG]');
$(this).data('changed',true); // set "changed=true" for current input
// Check if both input fields are changed
if(OG.data('changed') == true && FG.data('changed') == true){
//var calc = round(ADF(OG.val(),FG.val())*100, 2); // uncomment this
var calc = OG.val() * FG.val(); // comment this
$('.ADFbox').html(function(){
$('#Gravities input').data('changed',false); // set "changed=false" for next query
return '<div class="ADF">'+calc+'%</div>'
});
}
});
}
$(document).ready(main);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="Gravities">
<div>
<p><label class="originalGravity">OG: <input type='text' name='OG' value =""></input></label></p>
</div>
<div>
<p><label class="finalGravity">FG: <input type='text' name='FG' value=""></input></label></p>
</div>
</form>
<div class = 'ADFbox'>
<p>ADF:</p>
</div>

Categories