Duplicated script not showing result - javascript

This is my first question here, so pardon the naiveness please, thx.
I am currently building a calculator based on HTML, JS (+jQuery) and CSS. My calculator is a multi-input calculator that can count various things on a single webpage. For context, the calculator that I am building at the moment, is a gear calculator. It supposed to be able to calculate various items using various formulas. For the first item, it will be capable to calculate the module of a gear. This first calculation was successful with the following script:
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valZ = parseInt($('.jumlahGigi').val());
var valD = parseInt($('.diameterPitch').val());
var sum = valD/valZ;
$("input#resultModule").val(sum);
});
});
I duplicate the script to calculate other items but I don't forget to change the variables. This is the next script to calculate the amount of teeth on a gear:
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valM = parseInt($('.module').val());
var valD = parseInt($('.diameterPitch').val());
var sum = valD/valM;
$("input#resultAot").val(sum);
});
});
and this is the last script I wrote to calculate the diameter pitch:
$(document).ready(function(){
$('input[type="text"]').keyup(function () {
var valM = parseInt($('.module').val());
var valZ = parseInt($('.jumlahGigi').val());
var sum = valZ*valM;
$("input#resultDP").val(sum);
});
});
For the first item calculation, when I enter a number onto the input form, the result came out successfully. But for the other 2 calculations, the result won't came out. Can anyone maybe spot where my flaw lies?

Your issue is that $('.class').val() will take the value only from the first matching element, essentially $('.class').first().val().
In your fiddle, you have 2 of each input: .module, .diameter, .jumlahGigi.
Your calculations are working fine, but they are taking values from earlier inputs - eg diameter pitch takes teeth from module and module from the teeth input.
The easiest option is to use unique classes for each input.
//module
$(document).ready(function() {
$('input[type="text"]').keyup(function() {
var valZ = parseInt($('.moduleJumlahGigi').val());
var valD = parseInt($('.moduleDiameterPitch').val());
var sum = valD / valZ;
$("input#resultModule").val(sum);
});
});
//Amount of teeth
$(document).ready(function() {
$('input[type="text"]').keyup(function() {
var valM = parseInt($('.aotModule').val());
var valD = parseInt($('.aotDiameterPitch').val());
var sum = valD / valM;
$("input#resultAot").val(sum);
});
});
//Diameter Pitch
$(document).ready(function() {
$('input[type="text"]').keyup(function() {
var valM = parseInt($('.diameterModule').val());
var valZ = parseInt($('.diameterJumlahGigi').val());
var sum = valZ * valM;
$("input#resultDP").val(sum);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<div class="general">
<div class="module">
<label class="label"> Module </label>
<input type="text" class="moduleDiameterPitch" placeholder="Diameter Pitch">
<input type="text" class="moduleJumlahGigi" placeholder="Amount of Teeth">
<input type="text" disabled="disabled" id="resultModule" placeholder="Module">
</div>
<div class="AoT">
<label class="label"> Amount of Teeth </label>
<input type="text" class="aotDiameterPitch" placeholder="Diameter Pitch">
<input type="text" class="aotModule" placeholder="Module">
<input type="text" disabled="disabled" id="resultAot" placeholder="Amount of Teeth">
</div>
<div class="diameterPitch">
<label class="label">
Diameter Pitch
</label>
<input type="text" class="diameterJumlahGigi" placeholder="Amount of Teeth">
<input type="text" class="diameterModule" placeholder="Module">
<input type="text" placeholder="Diameter Pitch" disabled="disabled" id="resultDP">
</div>
</div>
The alternative is to use relative DOM navigation ($(this).closest(".calc").find(".module") - but as the calculations are very specific, it makes sense to name the inputs specifically for each calc.

Related

Calculate price based on markup and markup based on price using the same input fields

I have created 3 input fields Trade, Markup and Price. I would like for the user to enter a trade and then manipulate the price either by markup or by entering the price and the markup showing a reflection of that price.
I would like the calculation to be live and to not have to submit a button everytime to view changes.
I did split the code up into 2 separate scripts but that did not make a difference and I have also changed the addEventListeners to "change" but that still did not work. I have a felling I will need to add a IF statement between the 2 results somehow.
document.getElementById("trade").addEventListener("change", calculation);
document.getElementById("price").addEventListener("change", calculation);
document.getElementById("markup").addEventListener("change", calculation);
function calculation() {
var trade = parseFloat(document.getElementById("trade").value);
var markup = parseFloat(document.getElementById("markup").value);
var price = parseFloat(document.getElementById("price").value);
var markupresult = price / trade;
var priceresult = markup * trade;
document.getElementById("markup").value = (markupresult).toFixed(2);
document.getElementById("price").value = (priceresult).toFixed(2);
}
<div class="form-group"><label>Trade</label><input type="number" id="trade" name="trade"></div>
<div class="form-group"><label>Price</label><input type="number" id="price" name="price"></div>
<div class="form-group"><label>Markup</label><input type="number" id="markup" name="markup"></div>
Check the below snippet.
You can use a switch to change only one/vice versa.
Instead of change, you can use keyup which would provide you realtime output, (Whenever the user enter a number, the result will be calculated and shown).
document.getElementById("trade").addEventListener("change", calculation);
document.getElementById("price").addEventListener("change", calculation);
document.getElementById("markup").addEventListener("change", calculation);
function calculation(event) {
var trade = parseFloat(document.getElementById("trade").value);
var markup = parseFloat(document.getElementById("markup").value);
var price = parseFloat(document.getElementById("price").value);
var markupResult = price / trade;
var priceResult = markup * trade;
switch (event.target.getAttribute("id")) {
case "markup":
document.getElementById("price").value = priceResult.toFixed(2);
break;
case "price":
document.getElementById("markup").value = markupResult.toFixed(2);
break;
}
}
<div class="form-group">
<label>Trade</label><input type="number" id="trade" name="trade" />
</div>
<div class="form-group">
<label>Price</label><input type="number" id="price" name="price" />
</div>
<div class="form-group">
<label>Markup</label><input type="number" id="markup" name="markup" />
</div>

math function with jQuery

Trying to using jQuery do some basic math functions.
Step 1. User enter Gross weight, and Tare weight, my function auto generate Net weight, which is Gross weight minus Tare weight.(This step works)
Step 2. User enter Price per pound, my function use Price per pound times Net weight to calculate total cost.
So far my code looks like this, it returns the net weight but does not return the total cost:
<script>
$(document).ready(function() {
$(".sub").focusout(function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = gross-tare;
$("#net").html(Math.round(net*1000)/1000);
});
});
$(document).ready(function() {
$(".sub1").focusout(function() {
$("#total").html('');
var net = $("#net").val();
var ppp = $("#ppp").val();
var total = net*ppp;
$("#total").html(Math.round(total*1000)/1000);
});
});
</script>
And the HTML:
<input type='number' name='gross' id=gross class=sub>
<input type='number' name='tare' id=tare class=sub>
<p id=net name='net'></p>
<input type="number" id=ppp name="ppp" class=sub1/>
<p id=total name='total'></p>
Forgive me if I am making stupid mistakes as I barely know jQuery, this is just one requirement for my project that I am working on.
A few minor things:
-id=gross should have quotes id='gross'
-$("#net").val(); net doesn't have a value, its a p, so use text()
-you'll want to use parseInt or parseFloat
Example:
$(document).ready(function () {
$(".sub").focusout(function () {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = gross - tare;
$("#net").html(Math.round(net * 1000) / 1000);
});
$(".sub1").focusout(function () {
$("#total").html('');
var net = parseInt($("#net").text());
var ppp = parseInt($("#ppp").val());
var total = net * ppp;
$("#total").html(Math.round(total * 1000) / 1000);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type='number' name='gross' id='gross' class='sub'/>
<input type='number' name='tare' id='tare' class='sub'/>
<p id='net' name='net' class='sub1'></p>
<input type="text" id='ppp' name="ppp" class='sub1'/>
<p id='total' name='total'></p>
Put the class names/ ids or other attributes in quotes. They are parsed wrongly by the browser. Check using "firebug" or "inspect element".
Problem in your code: You are using '$("#net").val()', but $.val() works only on input fields but #net is a <p> tag, so get its text using $.html().
Your code should be like this
HTML:
<input type='number' name='gross' id=gross class="sub">
<input type='number' name='tare' id=tare class="sub">
<p id="net" name='net'></p>
<input type="number" id="ppp" name="ppp" class="sub1"/>
<p id="total" name='total'></p>
SCRIPT:
$(document).ready(function() {
$(".sub").focusout(function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = gross-tare;
$("#net").html(Math.round(net*1000)/1000);
});
});
$(document).ready(function() {
$(".sub1").focusout(function() {
$("#total").html('');
var net = parseFloat($("#net").html());
var ppp = parseFloat($("#ppp").val());
var total = net*ppp;
$("#total").html(parseFloat(total));
});
});

function to compute and input average speed

I have 3 input fields, distance, time and average speed. I would like the average speed field to be automatically computed to minimise user effort. As such I have come up with this function but it doesn't work:
$('#Avg Speed').click(function(event) {
var distance = $('#Distance');
var time = $('#Time');
var speed = distance / time;
$(this).append(speed);
});
Any ideas? Even better than clicking the field would be that the result automatically comes up once distance and time is completed. No doubt my code reveals what a novice I am at this stuff.
If your speed is auto generated is good to make it disabled if it's input.
Also may be best event you search for is blur
HTML part:
<label>Distance <input type="text" name="distance" id="distance"></label><br />
<label>Time <input type="text" name="time " id="time"></label><br />
<label>Speed <input type="text" name="speed " id="speed" disabled></label>
Jquery part:
$('#distance,#time').on('blur', function() {
var distance = $('#distance');
var time = $('#time');
var speed = $('#speed');
if(parseInt(time.val()) > 0 && parseInt(distance.val()) > 0)
speed.val(distance.val()/time.val());
})
Also if it will be good a idea to add measures for times, distance and speed
<input type="text" id="Distance">
<input type="text" id="Time">
<input type="text" id="Speed">
$('#Avg Speed').focus(function(event) {
var distance = $('#Distance').val();
var time = $('#Time').val();
var speed = distance / time;
$(this).val(speed);
});
try with an onKeyUp event, i'll give you an example:
HTML:
<input type="number" id="distance"></input>
<input type="number" id="speed"></input>
<input type="number" id="speed" onKeyUp="calcultate()"></input>
<Label id="result"></Label>
JS:
function calculate(){
//get all input values calculate your thing and then put it back //in the result, this will be called each time a user presses a key in the //last input field
$('#result').text(yourResult);
}

javascript how to calculate values in dynamically added fields with multiple rows

I had one row with three fields: received, issue, balance
<input type="text" name="rcv" class="rcv"/>
<input type="text" name="issue" class="issue"/>
<input type="text" name="blnc" class="balance"/>
I calculated the balance for each row easily, but how do I calculate more than one row?
Each row has receive, issue and balance fields.
How do I calculate each row's balance field?
I tried like this for multiple row but it's not working:
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = $('.t_rcv').val();
var totalRtn = $('.t_rtn').val();
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
you need to parse The value of textbox as it returns string not int
$('.t_rtn, .t_rcv').each(function(){
$(this).on('blur',function(){
var totalRcv = parseInt($('.t_rcv').val()) || 0;
var totalRtn = parseInt($('.t_rtn').val()) || 0;
// console.log( $('t_rtn').next('.consume').val() );
$('t_rtn').next('.consume').val(totalRcv-totalRtn);
});
If your code is being run on document.ready it will only be applied to elements which exist at that point.
You'd be better with :
$(document).on('blur','.t_rtn, .t_rcv',function(){
var val = $(this).val();
...
});
try this..
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
In addition to parsing the string values into integers you also need to use the correct selectors for those input elements. t_rtn is not the right class name, for example. And if doing this in rows you will want to grab the correct element from the current row (you already did this correctly for the consume field)
Fixed html (Example.. I chose to use div with class name = row):
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
<div class='row'>
<input type="text" name="rcv" class="receive"/>
<input type="text" name="issue" class="return"/>
<input type="text" name="blnc" class="balance"/>
</div>
Fixed code:
$(document).on('blur','.receive, .return', function()
{
var $row = $(this).closest(".row");
var totalRcv = parseInt($row.find('.receive').val()) || 0;
var totalRtn = parseInt($row.find('.return').val()) || 0;
$row.find('.balance').val(totalRcv - totalRtn);
});
I took the liberty of fixing some inconsistencies with the class names used. I tried to match them up to the variables for totalRcv and totalRtn so that now the balance shows as receipt minus return. If the user enters non-numeric data, it defaults the value to 0 before calculating.
Example fiddle here: http://jsfiddle.net/cp81g4nf/1/
I think problem is because you are subtracting 2 Strings. .val returns an String.
Convert them in number before subtracting like bellow
$('t_rtn').next('.consume').val((+totalRcv)-(+totalRtn));

Fields calculating only after a refresh

I apologize in advance for what I assume is a very basic question, but I am very new to scripting and would like to ask for some advice on a problem I am having.
Essentially I am creating a website that should sum the dollar amounts of two fields based on hours worked and return a total dollar amount. One of the fields has a fixed dollar amount and the other is a variable.
As far as I can tell the code should be working, but the field that should be user generated (esceptionalRate) seems to calculate correctly only after a page refresh, and then only on firefox... instead of automatically updating the total value when a change is made to the user field
code as follows:
<head>
</head>
<body>
<script>
$(document).ready(function () {
var standardRate = 110;
var exceptionalRate = $("#ex_rate").val();
var standardEntry = 0;
var exceptionalEntry = 0;
var totalVal = 0;
$("#Standard").on("change",function(){
standardEntry = $(this).val() * standardRate;
totalVal = standardEntry + exceptionalEntry;
$("#Amount").val(totalVal);
});
$("#Exceptional").on("change",function(){
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});
</script>
and here's the HTML side:
<input name="Standard" type="number" step="any" value="0" id="Standard" size="10" />
<input type="text" size="10" name="ex_rate" id="ex_rate" />
<input name="Exceptional" type="number" step="any" value="0" id="Exceptional" size="10" />
<td valign="top" nowrap="nowrap"><font size="2">Total Amount Requested </font></td>
<td><input name="Amount" type="text" id="Amount" size="35"/></td>
thanks in advance for all your wisdom and knowledge.
You have forgotten to close the $(document).ready function
Try:
$(document).on("change", "#Standard", function(){
And:
$(document).on("change", "#Exceptional", function(){
The problem is that your exceptionalRate variable is out of the scope of your calculation, and only gets set to the initial value upon the page loading. You need to move it within the change handler:
$("#Exceptional").on("change",function(){
exceptionalRate = $("#ex_rate").val();
exceptionalEntry = $(this).val() * exceptionalRate;
totalVal = standardEntry + exceptionalEntry ;
$("#Amount").val(totalVal);
});

Categories

Resources