Would like to format a field for currency in US Dollars. So if the user enters 14590.1 it will change it to 14,590.10. I would prefer not to even have the dollar sign, but my current code does have that.
I think what I have below is not bad, although I also want to check for a valid number and throw the user back in the field if it is not valid.
I thought this would be simple and there would be a function out there to do this, but I cannot find one.
Is there something better than what I threw together?
<?xml version="1.0" encoding="UTF-8"?>
<xp:view
xmlns:xp="http://www.ibm.com/xsp/core"
xmlns:xe="http://www.ibm.com/xsp/coreex">
<xp:scriptBlock
id="scriptBlock2"
type="text/javascript">
<xp:eventHandler
id="formatNumber"
submit="false"
event="onClientLoad">
<xp:this.script><![CDATA[
formatNumber = function(x) {
//Must remove $ and any commas
y = x.replace(',','');
z = y.replace('$','');
//Must fix to 2 decimal places
if ((typeof z) === 'string'){
z = parseFloat(z).toFixed(2)}
else {
z = z.toFixed(2)
}
//Now put it back in the field
XSP.getElementById("#{id:djCurrencyTextBox1}").value = parseFloat(z);
XSP.partialRefreshPost('#{id:djCurrencyTextBox1}');
}
]]></xp:this.script>
</xp:eventHandler>
</xp:scriptBlock>
<xp:inputText
id="djCurrencyTextBox1"
value="#{viewScope.a}"
styleClass="pull-right"
style="width:200px;text-align:right"
defaultValue="0">
<xp:this.converter>
<xp:convertNumber type="currency"></xp:convertNumber>
</xp:this.converter>
<xe:this.dojoAttributes>
<xp:dojoAttribute
name="input"
value="text-align: right">
</xp:dojoAttribute>
</xe:this.dojoAttributes>
<xp:eventHandler
event="onchange"
submit="false">
<xe:this.script><![CDATA[val = XSP.getElementById("#{id:djCurrencyTextBox1}").value
formatNumber(val);]]></xe:this.script>
</xp:eventHandler>
</xp:inputText>
</xp:view>
I tried using dojo but what I cannot get it to do is to accept a value if the user doesn't enter two digits for cents. If a user enters 1234 and tabs out of the field I want that to be modified to 1234.00. If they enter 1234.8 and tab it should be 1234.80. I I don't think I am adding the correct attribute:
<xe:djCurrencyTextBox
id="djCurrencyTextBox2"
value="#{doc.prjAmtColumn11}"
styleClass="pull-right"
style="width:100px;text-align:right"
defaultValue="0">
<xe:this.dojoAttributes>
<xp:dojoAttribute
name="input"
value="text-align: right" />
<xp:dojoAttribute
name="constraints"
value="fractional:yes">
</xp:dojoAttribute>
<xp:dojoAttribute
name="places"
value="2">
</xp:dojoAttribute>
</xe:this.dojoAttributes>
<xe:this.constraints>
<xe:djNumberConstraints
currency="USD"
fractional="auto"
type="currency"
places="2">
</xe:djNumberConstraints>
</xe:this.constraints>
<xp:eventHandler
event="onchange"
submit="false">
<xp:this.script><![CDATA[calculate();]]></xp:this.script>
</xp:eventHandler>
</xe:djCurrencyTextBox>