number as a % of another in javascript
number as a % of another in javascript
by Andrew Pougher
HTML
<div id="price-div1"><label>price1</label><input id="price1" type="text"></div>as a % of
<div id="price-div2"><label>price2</label><input id="price2" type="text"></div> is
<div id="rate-div"><label>rate</label><input id="rate" type="text">%</div>
<div class="rate-div"></div>
JavaScript
var number1 = 13;
var number2 = 24
$("body").append(Math.floor((number1 / number2) * 100));
$(".rate-div").html(parseFloat(parseInt(number1, 10) * 100)/ parseInt(number2, 10));
function txtpercentage(number1, number2) {
ch1 = number1;
ch2 = number2;
ch3 = (ch1 / 100) * ch2;
//$("#spanResult").html(Math.round(ch3,2));
$(".rate-div").before("<br>" + ch3.toFixed(2));
}
txtpercentage(parseInt(number1), parseInt(number2))
$(function() {
$("#price1, #price2").change(function() { // input on change
var result = parseFloat(parseInt($("#price1").val(), 10) * 100)/ parseInt($("#price2").val(), 10);
$('#rate').val(result||'').toFixed(2); //shows value in "#rate"
})
});