Make the jquery script smart - javascript

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

Related

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

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

How to get the value from the before selected radio?

In my case I have lines of radioboxes, every radio has a value. This value must be calculated and the result must be placed in a DIV.
My Problem is, I can't find a way to subtract the value of the choosen radion before.
let me show you a sample markup:
<table>
<tr>
<td><input name="tools" value="20" type="radio"></td>
<td><input name="tools" value="300" type="radio"></td>
<td><input name="tools" value="1000" type="radio"></td>
</tr>
<tr>
<td><input name="addons" value="5" type="radio"></td>
<td><input name="addons" value="10" type="radio"></td>
</tr>
</table>
<div id="result"></div>
JavaScript :
var radioClick = $('input[type="radio"]');
radioClick.on('change', function(evt){
// function sub or add the price...
// here is a shortcut of the add calc version...
var price = $(this).val(),
showPrice = $('#result').text(),
endresult = parseFloat(showPrice) + parseFloat(price),
$('#result').text(endResult);
});
With checkboxes it works fine, but in case of radioboyes I don't have a click-event to identify this on I must subtract.
in the first line we see the radios name=tools. here I take at first this one with value 20.
after that the value 20 will be shown in the#result, fine. But when I take now another radio name=tools the new value will add to the 20. and that is my problem. I don't know how to find the before selected radio button to get this value and subtract it.
Try using this:
html code:
<table>
<tr>
<td><input name="tools" class="test1" value="20" type="radio"></td>
<td><input name="tools" class="test1" value="300" type="radio"></td>
<td><input name="tools" class="test1" value="1000" type="radio"></td>
</tr>
<tr>
<td><input name="addons" class="test" value="5" type="radio"></td>
<td><input name="addons" class ="test" value="10" type="radio"></td>
</tr>
javascript:
<script>
var testPrice = 0;
var test1Price = 0;
var endprice = 0;
var price ='';
$('.test').click(function(){
price = $(this).val();
testPrice = price;
endPrice = parseFloat(testPrice) + parseFloat(test1Price),
$('#result').text(endPrice);
});
$('.test1').click(function(){
var price = $(this).val();
test1Price = price;
endPrice = parseFloat(testPrice) + parseFloat(test1Price),
$('#result').text(endPrice);
});
</script>
try it's demo on http://jsfiddle.net/rxrzX/
You don't need to substract. You can just find 2 value of 2 diff radio button : tools and addons. Then just add them and write in the div
You can get radio button value by :
$('input[name=radioName]:checked').val();
I think try this :
var radioClick = $('input[type="radio"]');
radioClick.on('change', function(evt){
// function sub or add the price...
// here is a shortcut of the add calc version...
var toolsprice = $('input[name=tools]:checked').val(),
var addonsprice = $('input[name=addons]:checked').val(),
endresult = parseFloat(toolsPrice) + parseFloat(addonsprice),
$('#result').text(endResult);
});
You could use an object literal that tracks the value, using a closure:
radioClick.on('change', (function()
{
var valTracker = {},
resultDiv = $('#result');//easier on the DOM
return function(evt)
{
valTracker[this.name] = valTracker[this.name] || 0;//get old value
var endResult = parseFloat(resultDiv.text()) + parseFloat($(this).val()) - valTracker[this.name];//subtract old value, too
valTracker[this.name] = parseFloat($(this).val());//set current value
resultDiv.text(endResult);
}
}()));
The valTracker object literal tracks the current radio value (the name of the element is used as property). I've also kept a reference to the $('#result') div in the closure. That way, you don't have to query the DOM every time the callback function is called.
Try using the code below: JSFIDDLE
var radio_groups = []
$(":radio").each(function(){
if (radio_groups.indexOf(this.name) == -1){
radio_groups.push(this.name);
}
});
$('input:radio').change(function(evt){
var resultPrice = 0;
$.each(radio_groups, function(){
curPrice = $(':radio[name="' + this + '"]:checked').val();
if (!(curPrice)){
curPrice = 0;
}
resultPrice = parseInt(resultPrice) + parseInt(curPrice);
});
$('#result').text(resultPrice);
});
This will work, even if you add more radio button groups. If you want this functionality only for specific groups, define the names in the array radio_groups instead of getting them from the document.

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

Multiplying Taxes and Adding to Total Amount

We don't always have to add taxes to order so I need a way that taxes will be bypassed by default unless specified.
So I have the following text box:
<input class="txt1" type="text" name="subtotal" value="" id="subtotal"
size="16" tabindex="42" onChange="enableBeforeUnload();"
onKeyUp="enableBeforeUnload();">
I have this text box working correctly-it sums the values.
I have two text boxes that I'm trying to multiply by the tax percent and display the total:
<input class="txt1" type="text" name="tax" id="tax" value="1" size="16" tabindex="42"
onChange="enableBeforeUnload();" onKeyUp="enableBeforeUnload();">
<input class="txt2" type="text" name="total1" value="" id="total1" size="16"
tabindex="42" onChange="enableBeforeUnload();" onKeyUp="enableBeforeUnload();">
I tried using the following with no luck:
var tax = +$("#tax").val(), // get tax and convert to a number
total = tax ? sum * tax : sum; // if tax is a non-zero number multiply
// otherwise just take the sum as is
and this:
totAmt.val(sum + sum*parseFloat(taxAmt.val()/100));
I could not implement either correctly.
Thanks in advance.
http://jsfiddle.net/thetylercox/jh2Ne/7/ i coul dnot get this to work correctly
http://soldbybillcox.com/treasure/demo.php its working fine here
For starters, you are calling:
$("#tax")
But you don't have an element with an id of tax. you could use:
$("input[name=tax]")
-edit->
So is the problem getting the values, or the logic in calculating the total?
You could throw your tax logic in a function:
function getTax(tax){
var taxFloat = parseFloat(tax)
if(isNaN(taxFloat)){
return 1;
}else{
return taxFloat;
}
}
Then use:
total = getTax($('#tax').val()) * sum;
And what's that plus doing in your formula?
Should just be:
var tax = $("#tax").val()
try adding a function to do your calculations
total = getTax($('#tax').val()) * sum;

Categories

Resources