I am trying to modify an existing line of JavaScript that I use often to format dollar amount entries in form fields so that the cents are displayed, even if not entered. I have used this for years:
<input maxlength="7" name="dollarvalue" size="8" onChange="javascript:this.value=parseFloat(this.value).toFixed(2);" />
…but it breaks if anything is entered other than numbers or a decimal…so I thought I could probably add a str.replace() to filter out the disallowed characters. It needs to be completely self-contained (as shown) so that I can easily add this one line onChange to a form field as needed. I got as far as this below, which still works for numbers, but is not stripping out other stuff. What am I doing wrong?
<input maxlength="7" name="dollarvalue" size="8" onChange="javascript:this.value=parseFloat(this.value.replace('/[^0-9\.]+/g','')).toFixed(2);" />
There shouldn’t be quotes around the regular expression. You’ll need to change
to