Issues with changing dynamic prices - javascript

I have a car rental company that offers pre-paid discount of 10%. I have formatted the total price correctly, but when someone adds an "Extra" to it, it stops changing the price total with the 10%.
This is the price field:
<span id="cashamount" class="additional xxlarge carrental_security_deposit" data-deposit="<?php echo $available_payments['carrental-paypal-security-deposit'];?>" data-deposit-round="<?php echo $available_payments['carrental-paypal-security-deposit-round'];?>"> - </span> <span class="additional xxlarge">ISK</span>
And this is the Javascript i use:
<script type="text/javascript">//<![CDATA[
window.onload=function(){
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
var Total = $("#cashamount");
var totalNumber = Number(Total.text().replace(/[^0-9\.]+/g,""));
Total.text((totalNumber * 1.1).formatMoney(2, '.', ','));
}//]]>
</script>
It's there onChange variable or something that monitors the changes to the price field and changes accordingly ?.
Any help on this is greatly appreciated.

You can use jquery to execute a function every time a specific event is fired, in your case something like the jquery change function should do the trick:
$('#idOfPriceField').change(function() {
// make the desired updates here
});

Related

JavaScript Formula Incorrectly Calculating (Implementation, syntax, or PEMDAS error likely?)

I'm working on a function that should take information about monthly mortgage payment amount, interest rate, downpayment, etc. and spit out the cost of home that the user could hypothetically afford.
The formula (I think...) is this:
And I have it in JS like this:
function formatMoney(number, c, d, t) {
var n = number,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))),
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
function calculateCost()
{
var cost = downpayment + ( monthly * ( Math.pow( 1 + ( interest / 12 ), term * 12 ) - 1 ) / ( ( interest / 12 ) * ( Math.pow( 1 + ( interest / 12 ), term * 12 ) ) ) );
cost = "$" + formatMoney(cost, 2, ".", ",")
return cost;
}
But it's spitting out answers that are way too big to be logical. Can anyone familiar with JS figure out where I'm going wrong, translating the formula to JS?

Force two decimals on this localisation function for large numbers [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have the following function that automatically adds the commas to an American numerical expression which is some way of localisation. I need a minor change to this function.
if I have 160 * 54.08 = 8.652,8 as input to the function what can I do to show the output as 8.652,80 with two decimal places? Right now the function outputs as 8.652.8
function Numberformat(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
function Numberformat(nStr) {
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? ',' + x[1] : ',0';//if there is no decimal
//force ",00"
x2 = x2.length < 3? x2 + "0" : x2;//if length of decimal + delimiter is
//less than 3 add an extra 0
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + '.' + '$2');
}
return x1 + x2;
}
document.body.innerHTML = Numberformat(160 * 54.08);//8.652,80
document.body.innerHTML += '<br>' + Numberformat(8560);//8.560,00
document.body.innerHTML += '<br>' + Numberformat(8560.0);//8.560,00
document.body.innerHTML += '<br>' + Numberformat(8560.1);//8.560,10
document.body.innerHTML += '<br>' + Numberformat(8560.01);//8.560,01
document.body.innerHTML += '<br>' + Numberformat(8560.009);//8.560,009
Check this answer:https://stackoverflow.com/a/149099/3025534
You can use:
var profits=2489.8237
profits.toFixed(3) //returns 2489.824 (round up)
profits.toFixed(2) //returns 2489.82
profits.toFixed(7) //returns 2489.8237000 (padding)
Then you can add the sign of '$'.
If you require ',' for thousand you can use:
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
And use it with:
(123456789.12345).formatMoney(2, '.', ',');
If you're always going to use '.' and ',', you can leave them off your method call, and the method will default them for you.
(123456789.12345).formatMoney(2);
If your culture has the two symbols flipped (i.e. Europeans), just paste over the following two lines in the formatMoney method:
d = d == undefined ? "," : d,
t = t == undefined ? "." : t,
I would do something like this
var n = '1.000,00';
if (wrongFormat(n)) {
n = n.replace(',', '#');
n = n.replace('.', ',');
n = n.replace('#', '.');
}
var val = 1*n;
//do something with val here

angular-rangeslider to use decimal, float values

using Daniel Crisp's angular range slider http://danielcrisp.github.io/angular-rangeslider/. . would like use floating values from min: 0 - max: 1
step of 0.1 (0, 0.1, 0.2, 0.3,...)
What if you do a math cur / 100 while min should be 0 and max 100?
got it. secret was in the filter:
app.filter('hourMinFilter', function () {
return function (value) {
if (value === 120) return 'All'
var h = parseInt(value / 100);// changed this
var m = parseInt(value % 100);// changed this
m = '0.' + m; // added this
var hStr = (h > 0) ? h + 'dollars' : ''; // changed this
var mStr = (m > 0) ? m + 'cents' : ''; // changed this
var glue = (hStr && mStr) ? ' ' : '';
return hStr + glue + mStr;
};
});
worked turned into dollars and cents

trailing zeros with comma functionality using php

Hi I've code in javascript which is working fine but same functionality I want in php language I find different sources on the internet but didn't get successes.
Javascript Code:
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d ? "." : d,
t = t ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
function trailingZerosWithComma() {
var costAmount = $("#costAmount").val();
if(costAmount != "") {
var costAmountReplace = parseFloat(costAmount.replace(/\,/g,''));
$("#costAmount").val((costAmountReplace).formatMoney(2, '.', ','));
}
}
<input type="text" name="costAmount" id="costAmount" onblur="trailingZerosWithComma();">
But I need this in php
Number.prototype.formatMoney = function(c, d, t){
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d ? "." : d,
t = t ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
var costAmountReplace = parseFloat(costAmount.replace(/\,/g,''));

How does Stack Overflow implement the character counter saying xyz characters left?

How does Stack Overflow do the character counter saying xyz characters left?
Probably something like (with jQuery):
$('#txtbox').keypress(function() {
var max = 500;
var textLen = $(this).val().length;
var textLeft = max - textLen;
$('#charCount').text(
textLeft + ' character' + (textLeft == 1 ? '' : 's') + ' left'
);
});
(I know it's lazy to not actually look and see how they do it, but here's a working example: http://jsfiddle.net/FishBasketGordo/hqex8/)
HTML:
<textarea id="text" onkeyup="charCount(this);"></textarea>
<span id="chars"></span>
JS:
var maxChars = 500;
function charCount(el) {
document.getElementById('chars').innerText = maxChars - this.value.length;
}
not tested, but that's the basics.
This can be done several ways but here is a link to some simple source code. The only for sure way to know how SO does it is to look into there compressed javascript.
http://javascript.internet.com/forms/character-counter.html
Have a look at this page on one of my sites http://www.bestvaluesolicitors.com/contact-us
Peek at the JS - you are looking for this function:
function ml(id,max,repeat){if($F(id).length>max){$(id).value=$F(id).substring(0,max);}$(id).next('div').update($F(id).length+' / '+max+' characters');if(repeat==true){setTimeout('ml("'+id+'",'+max+','+repeat+')',500);}}
Esentially it is a combination of a timer and counting the length of text in the textarea
Probably something like this:
var max = 1000;
document.getElementById('freddy').onkeypress =
document.getElementById('freddy').onkeyup =
document.getElementById('freddy').onkeydown = function(){
var count = this.value.length;
if(max < count){
this.value = this.value.substring(0,999);
return false;
}
setTimeout(function(){
document.getElementById('susan').innerHTML =
(max-count)+' characters left!';
},1);
};
http://jsfiddle.net/Paulpro/S4Dtu/
Here is the definition of StackExchange's charCounter() method. It's a little obfuscated, but you can find the logic if you dig through it:
charCounter: function(c) {
return this.each(function() {
var d = $(this).parents("form").find("span.text-counter");
var e = this;
var f = function() {
var j = c.min;
var l = c.max;
var k = c.setIsValid || function() {};
var h = e.value ? e.value.length : 0;
var i = h > l * .8 ? "supernova" : h > l * .6 ? "hot" : h > l * .4 ? "warm" : "cool";
var g = "";
if (h == 0) {
g = "enter at least " + j + " characters";
k(false);
} else {
if (h < j) {
g = j - h + " more to go..";
k(false);
} else {
g = l - h + " character" + (l - h != 1 ? "s" : "") + " left";
k(h <= l);
}
}
d.text(g);
if (!d.hasClass(i)) {
d.removeClass("supernova hot warm cool").addClass(i);
}
};
$(this).bind("blur focus keyup", a.DelayedReaction(f, 100, {
sliding: true
}).trigger);
});
}
And the comment text areas, for example, are set up like so (again, obfuscated):
var x = z.find("textarea");
x.charCounter({
min: 15,
max: 600,
setIsValid: A
});

Categories

Resources