TL;DR: Skip to the actual code if you just want the fix. The following paragraphs explains why it is happening.
The reason the decimal numbers aren't working is every single time the text box get edited by a single character, all numbers in all text boxes are converted to a float. If you type 1
into one of the boxes, the value gets passed to parseFloat
and gets converted to 1
(the same value). If you then press the 3
character, the text box says 13
, which gets passed to parseFloat
and returns the same value, 13
.
However, if you start typing 13.
, that gets passed to parseFloat
; JavaScript realizes the period is unnecessary*
, and places the value 13
in the text box. No matter how fast you type, JavaScript will keep wanting to trim off that "unnecessary" period before you can add extra digits to the end.
You can solve this by only running parseFloat
function (or changing the value in any way) on the text fields you are not currently typing in. I have emphasized the two lines in which "the magic happens":
$("input[type=text]").keyup(function () {
var number = parseFloat($(this).val());
var inc = parseFloat($(this).attr("inc"));
var newValue = number / inc;
var current = this; // <---- "current" is the text field that is currently being edited
$("input[type=text]").each(function () {
if(this != current) { // <--------------
if (isNaN(newValue * parseFloat($(this).attr("inc"))))
$(this).val(0);
else
$(this).val(newValue * parseFloat($(this).attr("inc")));
}
});
});
And a JS Fiddle of the code so you can test it: http://jsfiddle.net/RX2sL/27/
*
Technically the period gets trimmed off due to the String -> Float -> String
conversion, but it's easier to think of the period as being "unnecessary".