javascript - Convert number from text field to proper USD -
i have script on leaving text field
onblur="fora();"
converts user input number "number + usd" looks unprofessional. script is:
<script type="text/javascript"> function fora() { document.getelementbyid('field1').value = document.getelementbyid('field2').value +" usd"; } </script>
so converts "12345.75
" "12345.75 usd
". ughh.
do know how can convert number proper self? 12345.75
$12,345.75
my second, related question in same vain...
onclick="document.getelementbyid('field1').value = (math.round((parsefloat(document.getelementbyid('11091').value,2)*100))/100 + math.round((parsefloat(document.getelementbyid('1254.75').value,2)*100))/100).tofixed(2);"
can value field1 (12345.75) converted "$12,345.75"
thanks in advance.
function fora() { document.getelementbyid('field1').value = "$" + addcommas(document.getelementbyid('field2').value) +" usd"; } 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; }
check out example at: http://jsfiddle.net/cs67m/1/
the comma script from: http://www.mredkj.com/javascript/nfbasic.html have used before , has worked charm.
here updated example additional functionality requested: http://jsfiddle.net/cs67m/3/
html
number 1<input id="field1" value="$1,230.12"/><br> number 2<input id="field2" value="$1,230.12"/><br> sum<input id="sum" readonly=true/> <button id="submit">add</button>
js
function fora() { document.getelementbyid('sum').value = "$" + addcommas(getnumericvalue('field1') + getnumericvalue('field2')) +" usd"; } 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; } function getnumericvalue(id) { return stripalphachars(document.getelementbyid(id).value); } //source: http://www.27seconds.com/kb/article_view.aspx?id=31 function stripalphachars(pstrsource) { var m_strout = new string(pstrsource); m_strout = m_strout.replace(/[^0-9\\.]/g, ''); return parsefloat(m_strout); }
Comments
Post a Comment