Binding paragraph value to hidden input in jQuery - javascript

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

Related

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

Issue with simple calculation script

I'm trying to make a really simple calculator for my website.
Basically, I want people to be able to put in their weight into a text box, click "Calculate Dose" and then the script multiplies their weight by a number that I will set myself for each page.
Here is what I have right now. Not only does it not work, but it also stops one of my ads from displaying:
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()">
<input id="result" />
</div>
<script>
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight.value * 1;
result.value = dosage;
}
</script>
What's wrong with it?
You are missing closing tag /> in your button
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You already stored weight value
var weight = document.getElementById('inputweight').value;
So you dont need this var dosage = weight.value * 1;
So use var dosage = weight * 1;
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
this line:
var weight = document.getElementById('inputweight').value;
and this:
var dosage = weight.value * 1;
do not work together well. You are retrieving the value, then the value of that... which cannot work.
So, replace the second line with:
var dosage = weight * 1;
Besides: You should check the console for errors, it should show up there.
I assume (or, guess, more correctly) that the ad that is no longer working stops because the javascript execution is typically terminated after an error.
Just update this line (remove the value attribute which is already extracted above):
var dosage = * 1;
This will work but you might also want to add this for increased type safety (it parses weight as a number):
var dosage = parseInt(weight, 10) * 1;
In your code block you are missing a closing / at the end of the second input statement. Which should be giving you an issue in your html.
<input type="button" value="Calculate Dose" onClick="calculate()"/>
You also don't need weight.value again in the third line of your function. Instead it should be:
var dosage = weight * 1;
Fiddle demonstrating your example modified to work:
http://jsfiddle.net/x38ommxs/
function calculate() {
var weight = document.getElementById('inputweight').value;
var result = document.getElementById('result');
var dosage = weight * 1;
result.value = dosage;
}
<div>
<input id="inputweight" type="text" />
<input type="button" value="Calculate Dose" onClick="calculate()" />
<input id="result" />
</div>
Added missing closing tag on button
Changed dosage to multiply the value stored in weight by one.

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

Make the jquery script smart

There are 3 input fields.
Each has its own hidden input which helds value.
At this moment script works only for Bananas.(:-))
1 Banana is worth 1 banana OR 0.5 apple or 0.021 of a cookie(in other words 1 apple = 2 bananas, 46 bananas = cookie, 1 banana = 1 banana).
What I would like this script to do is to calculate values also for Apples and Cookies, and sum them up to show how much are they worth in "other" currencies.(for example show the price of 3 apples and 4 cookies in all 3 currencies)
I do realise that the code is very...well it would be a shame to call it code.
I just don't have any idea how to do it;
Any help would very appreciated.
Fiddle:
http://jsfiddle.net/eN7S6/9/
HTML:
<table>
<tr>
<td>
Apple<input name="inputone" id="inputone" class="calc" value="0"><span id="TotalOne"></span>
</td>
</tr>
<tr>
<td>
Banana<input name="inputtwo" id="inputtwo" class="calc" value="0"><span id="TotalTwo"></span>
</td>
</tr>
<tr>
<td>
Cookie<input name="inputthree" id="inputthree" class="calc" value="0"><span id="TotalThree"></span>
</td>
</tr>
</table>
<input name="multiplierone" id="multiplierone" class="calc" value="1" type="hidden" readonly>
<input name="multipliertwo" id="multipliertwo" class="calc" value="0.5" type="hidden" readonly>
<input name="multiplierthree" id="multiplierthree" class="calc" value="23" type="hidden" readonly>
<input type="button" id="update" value="Calculate" />
JQ:
$(document).ready(function() {
$('#update').click(function() {
var inputone = $('#inputone').val();
var multiplierone = $('#multiplierone').val();
var inputtwo = $('#inputtwo').val();
var multipliertwo = $('#multipliertwo').val();
var inputthree = $('#inputthree').val();
var multiplierthree = $('#multiplierthree').val();
var totalTotalOne = (inputtwo * multipliertwo);
var totalTotalTwo = (inputtwo);
var totalTotalThree = (inputtwo / multiplierthree / 2);
$('#TotalOne').text(totalTotalOne);
$('#TotalTwo').text(totalTotalTwo);
$('#TotalThree').text(totalTotalThree);
});
});
Well from what i gather from you description is that you want to get an amount that you have of a particular item. So if you have 10 bananas you want to calculate those 10 bananas against the other elements. The same goes for if you have 37 cookies you want to know how much its worth against the other items.
I believe that if you were to simplify your UI into two elements one being a input text field to enter amounts and another radio check collection, or it could be a selection field to select what type you have it will make better sense.
In your current setup you are not taking into account that your type(Apple, Banana, cookie) variable will change its only hard-coded to calculate bananas.
I quickly setup a jsbin to show you what i mean. Its just a start that may help you think of something else to do. Happy coding!
http://jsbin.com/EKisiGIK/10/edit
$(document).ready(function() {
$('#update').click(function() {
var inputone = parseFloat($('#inputone').val());
var multiplierone = parseFloat($('#multiplierone').val());
var inputtwo =parseFloat( $('#inputtwo').val());
var multipliertwo = parseFloat($('#multipliertwo').val());
var inputthree =parseFloat( $('#inputthree').val());
var multiplierthree = parseFloat($('#multiplierthree').val());
var totalTotalOne = (inputtwo * multipliertwo);
var totalTotalTwo = (inputtwo);
var totalTotalThree = (inputtwo / multiplierthree / 2);
$('#TotalOne').text(totalTotalOne);
$('#TotalTwo').text(totalTotalTwo);
$('#TotalThree').text(totalTotalThree);
});
});
Try this
One thing that you can do to make this problem simpler is to convert all currencies to a base currency before converting to their respective currencies. Using the example you have given i have converted all the currencies to their Cookie equivalent as it was the most valuable therefore removing the need to work with decimal values.
Change the HTML to
<input name="multiplierone" id="multiplierone" class="calc" value="23" type="hidden" readonly>
<input name="multipliertwo" id="multipliertwo" class="calc" value="46" type="hidden" readonly>
<input name="multiplierthree" id="multiplierthree" class="calc" value="1" type="hidden" readonly>
which is how many of each of the currencies it takes to make up one Cookie.
The following code can then be used to convert the currencies to Cookies
var base_total = inputone / multiplierone + inputtwo / multipliertwo + inputthree / multiplierthree;
var totalTotalOne = (base_total * multiplierone);
var totalTotalTwo = (base_total * multipliertwo);
var totalTotalThree = (base_total * multiplierthree);
this code will convert all the separate input values into their equivalent Cookie value. Once you have a total of all the fields as a cookie value it is a simple matter to convert that value back to all the respective currency values.
Fiddle

Calculating loan payment in Javascript

I am making a loan payment calculator on my website (www.kreditrunner.dk - In the bottom of the page).
EDIT: Problem solved with the following equation:
var princ = document.getElementById("amount").value;
var intr = document.getElementById("earlypercent").value/1200;
var term = document.getElementById("time").value;
document.getElementById("result").value = princ * intr / (1 - (Math.pow(1/(1 + intr), term)));
And also i used a keyup function instead. Cause when the key is pressed down, the input hasn't received the value yet, hence the wrong result :)
ORIGINAL POST:
I have my four inputs with respectively amount, interest rate per year in percent, payment period, and result.
<table>
<tr>
<td width="150">
<label for="amount">Lånebeløb (DKK)</label>
<input type="text" id="amount" name="amount" class="input-small">
<label for="earlypercent">ÅOP (%)</label>
<input type="text" id="earlypercent" name="earlypercent" class="input-small">
</td>
<td>
<label for="time">Løbetid (Mdr)</label>
<input type="text" id="time" name="time" class="input-small">
<label for="result"><b>Månedlig betaling (DKK)</b></label>
<input type="text" id="result" name="result" class="input-medium">
</td>
</tr>
</table>
For each of the first three input I have the listed calculations seen below which is derived from the following equation: http://www.wikihow.com/Calculate-a-Loan-Payment
$('#amount').keydown(function () {
var amount = document.getElementById("amount").value;
var earlypercent = document.getElementById("earlypercent").value;
var monthlypercent = earlypercent / 12 * 100;
var time = document.getElementById("time").value;
var negativetime = time * (-1);
var result = 1 + monthlypercent;
result = Math.pow(result, negativetime);
result = 1 - result;
result = monthlypercent / result;
document.getElementById("result").value = result * amount;
});
However, my result is weird as ****. As you can see when you try (e.g. with values, 1000, 10%, 12 months) the result is 8333.33 where it should have been around 83.33. Well actually it should be around 87.95.
So i could move the *100 in the montlypercent, however as you see when write an amount and tab to the next input field, the result changes even though the values are the same. Cant seem to get the equation right and the keydown function bothers me :/
Please help :)

Categories

Resources