views:

351

answers:

4

Hi,

I want to use JavaScript to restrict input on a text box to currency number formatting. For example:

<input type="text" value="2,500.00" name="rate" />

As given above, the text box should accept only numbers, commas and a period.

But, after the period it should accept two digits after numbers.

How do I accomplish this? Please clarify.

  • Gnaniyar Zubair
+1  A: 

If you want to do validation for your textbox, you can use Regular Expressions. If you want to restrict the input from the user, you can trap the keystrokes and filter out the ones you want them to enter using the onKeyDown event of the textbox.

Kirtan
Hi Kirtan,Thanks for your immediate response. i will try it out
Gnaniyar Zubair
A: 

These jQuery plugins can help..

http://www.texotela.co.uk/code/jquery/numeric/

http://plugins.jquery.com/project/aphanumeric

Vijay Dev
Hi Vijay,Thanks for your spontaneous response. i will try it out- Gnaniyar Zubair
Gnaniyar Zubair
+2  A: 

parseFloat can convert a string to a float and toFixed can set how many decimal places to keep.

function numToCurrency(num){
    return parseFloat(num).toFixed(2);
}


numToCurrency("4.2334546") // returns 4.23
Zach
Hi Zech,Thanks for your instance coding. i will try it out.- Gnaniyar Zubair
Gnaniyar Zubair
This actually doesn't do what your question originally intended... but could be merged into a more complete answer. I'll leave it up if it's useful.
Zach
A: 

You could use a jQuery's plugin called Alphanumeric

jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas. Have fun.

eKek0