I know this has been done a thousand times before but I’m having trouble with getting this right. I need to format the value of a text input for dollar amounts. No commas should be allowed. Only two decimal places should be allowed.
Examples of what should be allowed:
- 100
- 100.10
- $100
- $100.25
Below is my current incomplete regular expression. It currently allows multiple dollar signs to be included anywhere (not just at beginning), multiple decimal points to be included anywhere, and more than two decimal places which it shouldn’t.
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" language="Javascript">
$(function(){
jQuery('.dollarAmountOnly').keyup(function () {
this.value = this.value.replace(/[^$0-9\.]/g, '');
});
});
</script>
</head>
<body>
<input type="text" class="dollarAmountOnly"/>
</body>
</html>
I would greatly appreciate help. Thanks!
EDIT
Sorry, your question clearly asked for exactly two decimal places. This is what you want:
You have to escape your dollar sign, then you want two option digits after the decimal point:
Fiddle
Or, to allow arbitrary digits after the decimal point, you could use a Kleene closure instead of two optional digits