Reputation: 51
I have a rather complex formula that I want to recreate with code, I have set up a fiddle But I have no idea where to start with the JavaScript/jQuery?
Any help to get me started and point me in the right direction would be wonderful.
The formula I need is
(1/(1 - A %)) - 1 = B %
A = Percentage drop (#input)
B = Percentage gain (#output)
For example: If A drops with 25%, B has to increase 33% to break even
I would like the output to be displayed on click of the Calculate div, then in the future I would like to use a jQuery slider to change the input value and have the output change dynamically.
<div id="calc">
<div id="inputlabel">INPUT</div>
<input id="input">%</>
<div id="calculation">CALCULATE</div>
<h1 class="output">%</h1>
</div>
Upvotes: 0
Views: 1407
Reputation: 80653
This code will work:
$(document).ready(function() {
$('#calculation').click(function() {
var inp = parseFloat($('#input').val());
var out = parseFloat((1 / (1 - (inp / 100))) - 1);
out = parseInt(out * 100);
$('h1.output').text(out + ' %');
});
});
Check the updated fiddle.
Upvotes: 3
Reputation: 3579
Look here for the JSFiddle that does it: http://jsfiddle.net/LC8qE/
function calculate()
{
var A = parseInt(jQuery('#input').val()) / 100;
var B = (1/(1 - A)) - 1;
return Math.round(B * 100);
}
jQuery('#calculation').on('click', function(){
if(jQuery('#input').val() == '')
{ alert('enter a value!'); return false; }
var result = calculate();
jQuery('.output').text(result + '%');
});
Upvotes: 1