math function with jQuery - javascript

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));
});
});

Related

Duplicated script not showing result

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.

Binding paragraph value to hidden input in jQuery

I have a simple jQuery function to calculate the net weight by using gross weight minus tare weight. It looks like this and it is working:
$(".sub").focusout(function () {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
});
And my html currently looks like this:
<input type='number' name='gross' id='gross' class='sub' />
<input type='number' step="any" name='tare' id='tare' class='sub' />
<p id='net' class='sub1'></p>
<input type="hidden" name="hiddenNet" value=${net}/>
Notice the last line of the html I have a hidden input called hiddenNet and what I am trying to do here is bind the value of net with it. In other words, whenever p gets a net weight value based on the gross and tare, I want the value gets passed to hiddenNet. But what I am currently not getting any value, what did I do wrong?
why don't you simply set the value of your hidden field
$(".sub").focusout(function() {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
$("input[name=hiddenNet]").val($("#net").html());
});
<input type='number' name='gross' id='gross' class='sub' />
<input type='number' step="any" name='tare' id='tare' class='sub' />
<p id='net' class='sub1'></p>
<input type="hidden" name="hiddenNet" value="" />
If you're just using jQuery, the bind will not work. You need to set the value vía jQuery, check the line I added at last.
$(".sub").focusout(function () {
$("#net").html('');
var gross = $("#gross").val();
var tare = $("#tare").val();
var net = (gross - tare);
$("#net").html(Math.round(net * 1000) / 1000);
$("input[name='hiddenNet']").val(net);
});
JQuery is not a front-end templating framework like angularJS, you need to change the value of [name="hiddenNet"] after an event has been triggered.
You need to add something along the line of $('input[name="hiddenNet"]').val(net); to your function for the value to be updated correctly.
And if I you was would I would make my net variable contain the right value right away:
var net = Math.round((gross - tare) * 1000 / 1000);

JavaScript function Not Working with onchange attribute of input tag

I have been trying to replicate Duncan Donut Example from HEAD FIRST JAVASCRIPT, but the function subTotal() is never triggered by onchange event and when I look into HTML REFERENCE, I did not find any onchange event in list provided.
Duncan.html
<html>
<head><title>Duncan Online Donut's Service</title></head>
<script type="text/javascript">
function subTotal(){
document.write("working");
const TAXRATE = 0.095;
const DONUTRATE = 0.5;
var tax = 0;
var subTotal = 0;
var total = 0;
var cakedonut = parseInt(document.getElementById("cakedonut").value);
var glazedonut = parseInt(document.getElementById("glazedonut").value);
if(isNaN(cakedonut))
cakedonut = 0;
if(isNaN(glazedonut))
glazedounut = 0;
subTotal = (cakedonut + glazedonut)* DONUTRATE ;
tax = subTotal * TAXRATE ;
total = subTotal + tax ;
document.getElementById("subTotal").value = "$" + subTotal.toFixed(2);
document.getElementById("tax").value = "$" + tax.toFixed(2);
document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
<body>
<h1><b><i>Duncan Online Donut's Service</i></b></h1>
<form>
Name : <input id="name" type="text" name="name"/><br><br>
#no of cake donuts : <input id="cakedonut" type="text" name="cakedonut" onchange="subTotal()"/><br><br>
#no of glazed donuts : <input id="glazedonut" type="text" name="glazedonut" onchange="subTotal("/><br><br>
subTotal : <input id="subTotal" type="text" name="subTotal" /><br><br>
tax : <input id="tax" type="text" name="tax" /><br><br>
Total : <input id="total" type="text" name="total"/><br><br>
<input type="submit"/><br><br>
</form>
</body>
</html>
JSFiddle
The above is my code. I tried running this on IE and Chrome but in vain. Thanks in advance.
The problem is you have defined a variable and a function both with the same name subTotal and the variable declaration is overriding the function definition. Change the function name to anything say subTotal1 it will work.
JSBIN link
change your function name. don't use subTotal(); and don't use document.write("working");
function subTotalnew()
{
alert('working');
}
onchange="subTotalnew() it gonna be work after input blur.
oninput="subTotalnew() it gonna be work when input entering something.

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);
});

Calculate sum and multiply its value

I'm calculating the sum of a and b and putting it in text box named sum.
After I enter a number in number text box, it should calculate the final = sum * number.
<input type="text" class="txt_1_0" name="a" />
<input type="text" class="txt_1_0" name="b" />
<input type="text" id="sum" name="sum" />
<input type="text" class="number" name="number" />
<input type="text" class="final" name="final" />
I tried the following:
$(document).ready(function() {
$(".txt_1_0").change(function() {
var total = 0.00;
var textbox3 = 0.00; // this gonna be your third textbox
$(".txt_1_0").each(function() {
total += parseFloat(this.value) / 5;
});
textbox3 = $("#sum").val((total).toFixed(2));
});
});
How do I get the number value and calculate final?
You haven't actually added any function that would do the final calculation. So to multiply the sum (subtotal) with number, do the following:
$(".number").change(function () {
var final = $("#sum").val() * $(this).val();
$('.final').val(final);
});
Here is a demo - note that I have removed the division by 5 from your previous function as it didn't make sense from the the way your question was asked.
Or you can use keyup event with this jQuery code Fiddle
<script type="text/javascript">
$(document).ready(function(){
$('input[type="text"]').on('keyup',function(){
var a=parseFloat($('.txt_1_0:first').val())
var b=parseFloat($('.txt_1_0:last').val())
if(a && b){$('#sum').val(a+b)}
var number=$('.number').val()
if(number){
$('.final').val($('#sum').val()*number)
}
})
})
</script>

Categories

Resources