Christopher Green

Now with more Vitamin C!
posts - 41, comments - 30, trackbacks - 1

Currency TextBox with Javascript

This took me a long time so here it is for prosperity.  I started by looking at Ajax's masked edit field in order to enforce a simply currency field.  This was a waste of time and not up for the job.  I accomplished it with javascript instead.  Very simply, no symbols, just #####.## or ######,## with the cents being optional. 

Here is the script:

        function fnCurrencyOnly(o) {

            var sValue = o.value;

            var sKey = String.fromCharCode(window.event.keyCode);

            if (document.selection.createRange().text == sValue) {

                sValue = sKey;

            } else {

                sValue = sValue + sKey;

            }

            var re = new RegExp("^\\d+(?:\\.\\d{0,2})?$");

            if (!sValue.match(re))

                window.event.returnValue = false;

        }

 

    <div>

        <input type="text" onkeypress="fnCurrencyOnly(this);" />

    </div>

 

Enjoy!

Print | posted on Friday, April 24, 2009 2:35 PM |

Comments have been closed on this topic.

Powered by: