Not showing result with decimal discount value - javascript

I have a discount jquery calculator plugin.It is working. But percentage is not working with decimal values like Eg: 5.45%, 10.50% , 15.70%, 20.75% etc.. I created a Codepen project for it. Please check this Codepen link https://codepen.io/coderco/pen/gOeReMQ . Here is my codes. Please help me..
HTML
<input type="text" id="Amount" value="">
<input type="text" value="10.45" id="Discount">
<input type="text" id="Result">
Script
$(document).on("change keyup blur", "#Discount", function() {
var main = $('#Amount').val();
var disc = $('#Discount').val();
var dec = (disc / 100).toFixed(2); //its convert 10 into 0.10
var mult = main * dec; // gives the value for subtract from main value
var discont = main - mult;
$('#Result').val(discont);
});

It's because of toFixed(2). When you divide the value by 100 then there are 4 decimal places.
For example:
Amount = 100, Discount = 10.45
dec = (10.45/100) = 0.1045 (Calling toFixed(2) changes it to 0.10 that means 10 instead of 10.45).
In my suggestion add toFixed(2) to the final answer (discount), Instead of while calculating.

Related

Update input in real-time with jQuery

I'm creating a script for percentage calculation on my e-commerce, but I have a problem.
I want price update in real time as I write the percentage in the field.
So I made this:
<input type="text" name="cost" onchange="disc()">
<input type="text" name="discount" id="prized" onchange="updateInput()">
<input type="text" name="price" value="">
<script>
function updateInput(){
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
function disc(){
if($("#prized").val().length > 1) {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
}
<script>
But it does not work as I would like...
It does not update in real time, for "onchange".
So I did some research, and I found an interesting function: .keydown()
I have no idea how to use it in my script.
Someone can help me reach my goal?
Changing onchange by oninput should give you de behaviour you are looking for, the following snippet works for me:
function updateInput() {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
function disc() {
console.log(document.getElementsByName("discount")[0].value);
if($("#prized").val().length > 1) {
var discount = document.getElementsByName("discount")[0].value;
var cost = document.getElementsByName("cost")[0].value;
document.getElementsByName("price")[0].value = cost - (cost * (discount / 100));
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="cost" oninput="disc()"> <br><br>
<input type="text" name="discount" id="prized" oninput="updateInput()">
<input type="text" name="price" value="">
Couple of things: There's no need to use getElementBy* when using jQuery, there's no need to write the same function twice.
On input (rather than change or keyup) of both fields, run the function
$(function(){
$('#prized, #cost').on('input', function(){
var discount = $('#prized').val();
var cost = $('#cost').val();
var price = cost - (cost * (discount / 100));
$('#price').val(price);
})
});
https://jsfiddle.net/popnoodles/npgvmLkc/2/
I see 2 errors here:
First, you are not converting the values of the input fields to numbers; use parseInt() for this.
Second, declare your number inputs as such using ´type="number"´. This increases usability, as you will see.
Answer to your question:
If you use parseInt() in updateInput() and use onkeyup="updateInput" (or even better onkeypress="updateInput()" this should work. See this jsfiddle: http://jsfiddle.net/da5d92bk/
$("input[name='discount']").bind('input propertychange', function() {
//do your update here
}
Just try to use keyup listener like below.
$(document).ready(function() {
var copyField = $('#copyvalue'); //field where you want to copy
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
copyField.val($(this).val());
}
});
});
$('#idofelement').keydown(function() {
...
});

jQuery change text box value not working

I'm trying to display total price in sum label by multiplying qtyTxt value (user entered) with price. But it doesn't work, the if statement is never reached.
<input type="text" name="qtyTxt" value="1" size="2" style="width: 25px"/>
<label id="price">${adClicked.price}</label>
<label id="sum">${adClicked.price}</label>
<input type="hidden" name="id" value="${adClicked.id}"/>
<script>
$(".qtyTxt").bind('change', function () {
var sum=$(("#price").val())* ($(this).val());
$("#sum").val('Rs.'+sum);
});
</script>
There are no errors in the console and $("#sum").val('Rs.'+sum); works fine.
1) Use parseInt() or parseFloat() The parseInt() function parses a string and returns an integer.
2) Another mistake Don't use val() for label instead of use text() for label
var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
code be
$(".qtyTxt").bind('change', function () {
var sum= parseInt($("#price").text() , 10) * parseInt($(this).val() ,10);
$("#sum").text('Rs.'+sum);
});
Two issue:
1) You have error in your code, $(("#price").val()) should be $("#price").text() or $("#price").html()
2) You need to parse the values before doing mathematical calculation:
var sum=parseInt($("#price").text(),10)*parseInt($(this).val(),10) ;

Onchange to add 2 digits after decimal points

I have a receipt that I am working on that does the math for me. I need the results to show up as dollar values.
My HTML:
<input type="text" name="copy1" id="copy1" size="4" maxlength="10" onchange="calculate(this.value)">
<input type="text" name="copycosts" id="copycosts" size="4" VALUE=""/>
My JavaScript:
<script type="text/javascript">
function calculate(){
var copy1value = parseFloat(document.getElementById("copy1").value, 10);
document.getElementById("copycosts").value = copy1value * 0.50;
}
</script>
How do I add 2 decimal places after the multiplication is completed? For instance 13 * 0.50 = 6.5 -- I want it to say 6.50.
Thanks in advance.
Use toFixed() (which will convert the number to a string):
document.getElementById("copycosts").value = (copy1value * 0.50).toFixed(2);
If you need to manipulate this number in future, you'll need to use parseFloat():
var numFromCopycosts = parseFloat(document.getElementById('copycosts').textContent);
References:
Number.toFixed().
parseFloat().
Use below code to also round the number:
(Math.round(copy1value * 0.50 * 100) / 100).toFixed(2);
Example
1.345 will be rounded off to 1.35
Added jsfiddle: http://jsfiddle.net/FQTqk/297/
You can use toFixed:
var val = copy1Value.toFixed(2);

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