Return if nonnumeric or zero?!

I’m trying to make this golfscorecard script and it is working allmost correct…

It counts the numbers as it should and if a user inserts a nonnumeric value like “-” it counts that as 11. Great. But I also want to count “0” as 11 but not sure how to do so…

Here is my script:

// Makes sure variable is a number
function validNum(nmbr)
{
// forces variable into integer type
nmbr = (nmbr * 1);

// Checks if variable is Not a Number
if(!isNaN(nmbr))
// If a number, return value
return nmbr;
else
// If not a number, return eleven
	return 11;
}

The full script can be testet at http://mdesigns.dk/autotab.php

Hoping for help and thanks in advance…

You don’t want a normal number to be returned when it’s 0, so you add that on as another condition. We can also replace 11 with a constant, so that there’s no mystery about what the value of 11 is supposed to mean.


window.SCORE_ROUND_DEFAULT = 11;
...
if(!isNaN(nmbr) && Number(nmbr) > 0) {
    return nmbr;
} else {
    return SCORE_ROUND_DEFAULT;
}

In fact, because any valid number will be greater than 0, you don’t need the !isNaN part anymore.


if(Number(nmbr) > 0) {
    return nmbr;
} else {
    return SCORE_ROUND_DEFAULT;
}

So you can now condense that all down to a ternary operation:


return (Number(nmbr) > 0) ? nmbr : SCORE_ROUND_DEFAULT;

Or, if you want to get tricksy…


return Number(nmbr) || SCORE_ROUND_DEFAULT;

Resulting in a final function of:


window.SCORE_ROUND_DEFAULT = 11;

function validNum(nmbr) {
    return Number(nmbr) || SCORE_ROUND_DEFAULT;
}

The only problem with this is that when I change it to some of your examples it messes up the rest of the script… Whenb I type a number in the first field, the sum filed starts out with 90 something and it should sum the numbers I type…

Try it here at http://mdesigns.dk/autotab.php

Are you passing empty strings in there too? Then it’s not just numbers that are being validated.
You also need to check if it’s an empty string.

So, carrying on from the above, you could have:


window.SCORE_ROUND_DEFAULT = 11;
function validNum(nmbr) {
    return (nmbr > '') && (Number(nmbr) || SCORE_ROUND_DEFAULT);
}

AND YEEESSS!!! It works :slight_smile: Thanks alot Paul… Your the man :wink:

Although to be fair, it would be easier to understand if it were just:


window.SCORE_ROUND_DEFAULT = 11;

function validNum(nmbr) {
    if (nmbr > '') {
        return Number(nmbr) || SCORE_ROUND_DEFAULT;
    }
    return 0;
}