3

Everything in my script works perfectly except for my last "if" statement, it's failing to execute and I cannot figure it out for the life of me! I know I have an error somewhere but just can't work out why, I'm new to JavaScript.

Here's what I'm trying to achieve on the last statement:-

If "AgeGrade" variable matches "Expression" variable then accept value and change value entered to 2 decimal points. E.g. If 5.999 entered then change to 5.99

Here's the code:-

function agegrade() {

    var AgeGrade = document.submitrunnertime.AgeGrade.value;
    var expression = /^[0-9]*\.?[0-9]*$/

    if (AgeGrade == null || AgeGrade == "") {
        document.submitrunnertime.AgeGrade.value = "-1";
        return true;
    } else if (AgeGrade != document.submitrunnertime.AgeGrade.value.match(expression)) {
        alert("Error - Need a number!");
        return false;
    } else if (AgeGrade == document.submitrunnertime.AgeGrade.value.match(expression)) {
        document.submitrunnertime.AgeGrade.value = AgeGrade.toFixed(2);
        return true;
    } else
        return false;
}

Any help would be greatly appreciated.

Jamiec
  • 133,658
  • 13
  • 134
  • 193

2 Answers2

0

you can try this. i have use it in many javascripts for rounding off

document.submitrunnertime.AgeGrade.value = Math.round(AgeGrade * 100) / 100;
Vikky
  • 752
  • 3
  • 15
  • 35
0

Your last if statement probably fails with an error like: AgeGrade.toFixed is not a function.

How can you fix this?

The .value() method you're using returns a string. The method .toFixed(), however, works with numbers only (MDN doc). Before invoking it, try converting AgeGrade to float:

document.submitrunnertime.AgeGrade.value = parseFloat(AgeGrade).toFixed(2);
Para
  • 3,681
  • 4
  • 23
  • 34
  • Thanks for the input. Although this has now allowed me to submit a value it's rounding the number up rather than stripping the number precisely to 2 decimal places - any ideas? – Craig Smith Jan 26 '15 at 14:04
  • As already mentioned, please have a look at this answer: http://stackoverflow.com/questions/4187146/display-two-decimal-places-no-rounding – Para Jan 26 '15 at 14:22
  • In your specific case, it translates to: `Math.floor(parseFloat(AgeGrade) * 100) / 100` – Para Jan 26 '15 at 14:23