// get the value from the form field
var cop = document.getElementById('cop').value;
//strip out all non-numbers, except a decimal and turn into a float
cop = parseFloat(cop.replace(/[^.0-9]/g,''));
// if it still isn’t a number (user had nothing in the field), make it 0
cop = isNaN(cop) ? 0 : cop;
I remember when I was very new to JavaScript and programming in general, and didn’t know to use parseFloat and parseInt. If you forget to do that for a value you have pulled from a input box, JavaScript will typically concatenate the value, as it treats it as a string:
// num = 6 (as a string)
Var num = document.getElementById('cop').value;
//outputs “65†instead of 11
alert(num + 5);
Next, I had to display the damn thing like this “$30,000.06â€. I started with a regular expression I have used in PHP before: /(?<=\d)(?=(?:\d\d\d)+$)/ . But javascript complained about “?<=†which is a positive lookbehind. Apparently, JavaScript doesn’t support it. Digging into my books, I found toLocaleString(), which seemed to meet my criteria. In fact, it works without a problem in Internet Explorer (at least 6.0), but it exhibits some strange behaviors in Firefox. In Firefox, it doesn’t display the “.00†if the number doesn’t already contain it and it will only display one decimal place without the trailing “0â€. It wasn’t a major problem, but an annoyance nonetheless. I tried using toFixed(2) and then toLocaleString(), but it still didn’t work in Firefox and rather than writing extra code, I let it be.
One final note. Using the CSS selector :disabled doesn’t work in Internet Explorer. I wanted to hide input boxes I used to display the numbers and disabled them. But in Internet Explorer, it ignores any “font-color†declarations and outputs grey text, so it will look different than the rest of the text. I just hide the input boxes, and left them as enabled…