OnSave Javascript for CRM 2011 quote product - javascript

I have an script on the quote product which I want to update the tax value when saving the form. But, it did update the tax according previous values of the fields. The script is as:
function tax ()
{
var val0 = Xrm.Page.getAttribute("baseamount").getValue();
var val1 = Xrm.Page.getAttribute("manualdiscountamount").getValue();
val2 = val0 - val1;
val2 = val2 * 0.05;
Xrm.Page.getAttribute("tax").setValue(val2);
}
For example, if the base amount is 10 and the manual discount is 1 on the create of the quote product, then the tax updates to 0. If after save, I change the base amount to 20 and manual discount is 1, then the tax is updated to 0.45! Mean that, it calculates the tax based on the previous values of the fields!

You are facing this issue because you get the baseamount value before CRM updates it.
baseamout is calculated after the form is saved, so you need to calculate the value by hands as this simplified example:
function tax ()
{
var priceperunit = Xrm.Page.getAttribute("priceperunit").getValue();
var quantity = Xrm.Page.getAttribute("quantity").getValue();
var val0 = priceperunit * quantity;
var val1 = Xrm.Page.getAttribute("manualdiscountamount").getValue();
val2 = val0 - val1;
val2 = val2 * 0.05;
Xrm.Page.getAttribute("tax").setValue(val2);
}
pay attention that there is also the field for volume discount and the product can be also a write-in.

Related

Javascript populating hidden fields on mouseover - Before click

Looking for a solution to another problem I cam across the ability to run javascript on mouseover
I'd like to run this:
$(document).ready(function(){
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
}
When a user mouses over my submit button
When the script runs I'd like it to populate these fields which are then included in the form action
<input type="hidden" name="repay" id="repay_input" value="">
<input type="hidden" name="interest" id="interest_input" value="">
Right now it doesn't seem to work but this may be because I've missed a small thing or it just won't work entirely
Thank you - If anyone has a better idea on how to achieve my aim please let me know, I've tried PHP but no joy
Button for clarity
<button class="col-sm-4 enter-button" type="submit" name="submit" onmouseover="return myPayment()" value="Calculate">Calculate Payments</button>
Update:
I tweaked the javascript and the button but then missed off naming the form to match the reference in the JS
Also my mortgage calculations were WAY off due to the way the form collects % rate
Declare your function outside of jQuery's document.ready wrapper, and your button only needs to look like this:
function myPayment()
{
var value = document.mortgagecalc.value_input.value;
var rate = document.mortgagecalc.rate_input.value;
var term = document.mortgagecalc.term_input.value;
var deposit = document.mortgagecalc.deposit_input.value;
var fee = document.mortgagecalc.fee_input.value;
var totalloan = ((value + fee) - deposit) * 1 + rate;
var totalinterest = (totalloan * 1 + rate) - totalloan;
var months = (term * 12);
var repay = totalloan / months;
var interest = totalinterest / months;
// Calculate mortgage payment and display result
document.getElementById('repay_input').value = repay;
document.getElementById('interest_input').value = interest;
}
<button onmouseover="myPayment()" ...></button>

How to calculate tax percentage in jQuery?

This is my first time asking a question here, so I hope I'll do it correctly.
Just to give context, I'm developing a small website where lawyers can buy a digital version of some legal documents, but I'm having trouble calculating tax on the total cost.
The taxes are calculated with two rates used in the province of Quebec, Canada: GST (5%) and QST (9.975%). Both rates are calculated using the subtotal amount. Here's what I tried so far:
$("#formchoix #checkall").click(function () {
var tps = 0.05; //5%
var tvq = 0.09975; //9.975%
var subtotal = 0;
var total = 0;
if ($("#formchoix #checkall").is(':checked')) {
$("#formchoix input[type=checkbox].checkchoix").each(function () {
//check all forms
$(this).prop("checked", true);
$(".checknom").prop("checked", true);
$(".checkid").prop("checked", true);
subtotal += 15; //each form is 15$
$('#subtotal').html(subtotal + '.00$'); //subtotal shown to user
var taxes = subtotal * tps * tvq;
total = subtotal + taxes;
$('#totalcost').html(total.toFixed(2) + '$'); //total shown to user
$('#inputTotal').val(total.toFixed(2)); //value to be sent to server
});
} else {
$("#formchoix input[type=checkbox]").each(function () {
//reset everything: checkboxes, value and total shown to user
$(this).prop("checked", false);
$(".checknom").prop("checked", false);
$(".checkid").prop("checked", false);
subtotal = 0;
total = 0;
$('#subtotal').html('0.00$');
$('#totalcost').html('0.00$');
$('#inputTotal').val('0.00');
});
}
});
The above code doesn't give me the right number though. For example, if my subtotal is 30$, it will show 30.15$ instead of 30.49$ like it's supposed to (based on a tax calculator online).
I've also tried using values like 1.05 and 1.09975 and multiplicating them to the subtotal directly using total = subtotal * tps * tvq, but the total gave me 30.64$ (if the subtotal is 30$ like my previous example)
Clearly what I did is wrong, so how can I make sure the total is right?
30 * 0.05 * 0.09975 = 0.149625, which is rounded to 0.15 by calling toFixed(2). Math doesn't lie. As others suggested, you're taxing taxes.
var taxes = subtotal * tps * tvq;
total = subtotal + taxes;
should be changed to
total = subtotal + subtotal * tps + subtotal * tvq;
or
total = subtotal * (1 + tps + tvq);

How do I round the sum of two function returns that are stored within a variable?

I am using a function calculateTotal() for a form. Within this function is a variable that stores the sum of two other function returns. Depending on user input in the form, the sum can contain several decimal points. i.e. 76.6666666666. I would like to know if I can round this sum before it is displayed? I have tried Math.round(theWholeThing), doesn't work.
I don't know how I would round the number because it can change with user input to the form.
Same with parseint.
function calculateTotal()
{
var theWholeThing = areaTimesType() + getSetUp();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For grow space $"+theWholeThing + "\u00A0 \u00A0per month";
}
Try toFixed
(76.6666666666).toFixed(); => 77
(76.6666666666).toFixed(1); => 76.7
Your code will look like this
function calculateTotal()
{
var theWholeThing = areaTimesType() + getSetUp();
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total Price For grow space $"+(theWholeThing).toFixed(2) + "\u00A0 \u00A0per month";
}
Where are you running Math.round()? Maybe you're not catching the result of the round() function. Try something like:
divobj.innerHTML = "Total Price For grow space $"+ Math.round(theWholeThing) + "\u00A0 \u00A0per month";
Better yet, round the results when you declare theWholeThing:
var theWholeThing = Math.round(areaTimesType() + getSetUp());
Just try this one :
For 2 digit = Math.round(num * 100) / 100
For 3 digit = Math.round(num* 1000)/1000
Detail for this function you can check in
About Math.round

How do I get cart checkout price exact to the penny using Javascript?

How do I get cart checkout price exact to the penny using Javascript?
Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test.
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
var newCartTotal = (cartTotal - pricediscount).toFixed(2)
that will give you the value, but it will be a string. If you need it to stay numeric, use:
var newCartTotal = ((cartTotal - pricediscount * 100) << 0) / 100;
You need to round the discount for each line item: priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line).
I think you left out a line saying discountAmount += priceDiscount.
modify your code to :
priceDiscount = parseFloat( (subtotal * itemDiscountPercent).toFixed(2) );
and:
newCartTotal = parseFloat( (cartTotal - priceDiscount).toFixed(2) );

In JavaScript doing a simple shipping and handling calculation

I am having trouble with a simple JavaScript calculation. My document is supposed to add $1.50 to an order if it is $25 or less, or add 10% of the order if it is more then $25. The exact problem is:
Many companies normally charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box.
This is my code:
var price = window.prompt("What is the purchase price?", 0);
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
When testing I enter a number in the prompt box, and instead of calculating as if I entered a number it calculates as if I entered a string. i.e. i enter 19 and it gives me 191.5 or I enter 26 and it gives me 262.6
Using parseFloat will help you:
var price = parseFloat(window.prompt("What is the purchase price?", 0))
var shipping = parseFloat(calculateShipping(price));
var total = price +shipping;
function calculateShipping(price){
if (price <= 25){
return 1.5;
}
else{
return price * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
See it working at: http://jsfiddle.net/e8U6W/
Also, a little-known put more performant way of doing this would be simply to -0:
var price =window.prompt("What is the purchase price?", 0) - 0;
(See: Is Subtracting Zero some sort of JavaScript performance trick?)
Be sure to comment this, though as its not as obvious to those reading your code as parseFloat
you can easily convert a string to a number
http://www.javascripter.net/faq/convert2.htm
basically JS provides parseInt and parseFloat methods...
Actually, you need to cast your text results into float values using parseFloat()
http://www.w3schools.com/jsref/jsref_parseFloat.asp
See my answer to the s/o question "Javascript adding two numbers incorrectly".
A bit of redundant multiplication, but your problem is that the numbers that are being inputted are treated as strings, not numbers. You have to convert them to floating point numbers:
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price)
{
if (price <= 25)
{
return 1.5;
} else {
return price / 10
}
}
window.alert("Your total is $" + total + ".");
var price = parseFloat(window.prompt("What is the purchase price?", 0));
var shipping = calculateShipping(price);
var total = price + shipping;
function calculateShipping(price){
var num = new Number(price);
if (num <= 25){
return 1.5;
} else{
return num * 10 / 100
}
}
window.alert("Your total is $" + total + ".");
This should do it for you.

Categories