想要爲美元格式化貨幣字段。所以如果用戶輸入14590.1,它會將其更改爲14,590.10。我寧願不要有美元符號,但我目前的代碼確實有這個。客戶端javascript格式編號(貨幣)
我覺得我下面有什麼不錯,雖然我也想檢查一個有效的數字,並且如果無效的話把用戶帶回現場。
我認爲這將是簡單的,那裏會有一個功能來做到這一點,但我找不到一個。
有什麼比我扔在一起更好?
<?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>
我試過使用道場,但我無法做到的是接受一個值,如果用戶沒有輸入兩位數的美分。如果用戶輸入1234並且選項卡不在該字段中,我希望將其修改爲1234.00。如果他們輸入1234.8並且製表符應該是1234.80。我,我不認爲我將正確的屬性:
<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>
這可能會幫助:http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript/9318724#9318724 –
這隻要(a)你的代碼按預期工作,(b)你的代碼是真實代碼而不是代碼示例,並且(c)您的代碼包含在問題的主體中。如果您希望通過同行評審來改進代碼的各個方面,請將其發佈在代碼評審中。 –
看看cleave.js,如果你只想格式化UI中的值並將實際的數值存儲在數據庫中,我昨天才發現它(所以沒有任何經驗),但它可能會訣竅。 –