4

I have a visualforce table where I'm creating a discount calculator. Basically user inputs a discount percentage and the table on the visualforce updates automatically to show you the updated price of a product after the user has entered a discount percentage.

Example of what it looks like on visualforce

enter image description here

The Before Discount fields are already set and cannot be changed. The Discount Amount and After Discount columns change depending on the values the user inputs into the Discount Percentage column.

I'm trying to format the Discount Amount Current and After Discount Currency so that it appears as currency i.e. 28,732.14. Aka, it should have commas separating the thousands from the hundreds. However, this is proving difficult to do with VisualForce since the way to format currency is through the following means:

 <apex:outputText value="{0, number, ###,###.##}"  id="TotalServiceId">
                            <apex:param value="{!TotalService}"/>
                        </apex:outputText>

However, because I'm using Javascript to automatically calculate the values and enter it into Discount Amount and After Discount, I don't actually have an object to place in the apex:param value. The Javascript looks for the ID where it needs to place the value and places it there.Thus My output Text value looks like this:

 <apex:outputText value="{0, number, ###,###.##}"  id="TotalServiceId">
                            <apex:param value=""/>
                        </apex:outputText>

My question is whether it's possible to format the Discount Amount and After Discount amounts currency when using Javascript to automatically enter values rather than tying apex:param value to an object from the controller.

6

You will have to write a java script function that will append , in your value. You can use below java script function -

function addCommas(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;
}

Use below code to override inner HTML of component -

document.getElementById('elementID').innerHTML = addCommas(Value);
4

VF tags (such as <apex:outputText>) are evaluated on the server and rendered as HTML to be sent to the browser, but your JavaScript is executing in the user's browser - the server won't see the data as the JavaScript is inserting the values directly. You will need to format the value using JavaScript; this thread on StackOverflow discusses how.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.