1

I'm trying to change the value on the page while when loaded and changing the currency with a simple calculation.

If any one can help me that be great,,

here is my code:

<head>
<script type="text/javascript">
function myscript() {
var input = document.getElementById('span1').innerHTML;
output = '$19,999.9 AUD';
document.body.innerHTML = document.body.innerHTML.replace(input,output);
}
</script>
</head>

<span id="span1" class="text field">$9,999.9 USD</span> 
<body OnLoad = "myscript();">
</body>

So basically I want to know how to make it take ONLY the numbers from id="span1" text field and do a simple calculation like + 10 and replace USD with AUD without losing the , and .

I have tried to make use of parseInt but didn't get it to work.

Thanks you in advance :)

EDIT: Please NOTE that the span1 value is dynamic and always changing

3 Answers3

1

A simple way is to just grab the numbers from the string.

var regpattern = /[^0-9.-]+/g;
var output= parseFloat(input.replace(regpattern , ''));
output += 10;

I would also recommend that the currency type USD and AUD not be part of the span1 but be part of span2 that is shown right after. This way the parsing doesn't need to handle it.

parapura rajkumar
  • 24,045
  • 1
  • 55
  • 85
  • perfect thanks, would you be able to tell me how to not lose the , and . ? the output only displays the calculation without the , – Dang Thi My HA Nov 19 '11 at 20:32
  • You will lose them. You might have to write functions to put them at the right place. Currency manipulation is kinda tricky. Some countries use , at the 1000th place some don't. Look at @Keith's solution if you need more that simple addition – parapura rajkumar Nov 19 '11 at 20:34
  • sorry I'm a beginner and kinda don't understand much, would it work if i re-edit again the givin value? – Dang Thi My HA Nov 19 '11 at 20:45
0

This post might be of some help: Currency Math in JavaScript.

It explains how to use parseFloat combined with string.replace to accomplish parsing currency strings to floats and then doing calculations

Community
  • 1
  • 1
Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
-1

http://jsfiddle.net/ArXbL/1/ is working for you

frosty
  • 21,036
  • 7
  • 52
  • 74