Just recently I had to implement an HTML form that allows users to enter percentage values. Like every good programmer I added client-side validation to check that the input values are between 0 and 100.
My first reaction was to restrict the maxlength attribute of the input field to 3 characters only. Even though this is a good and recommended practise there was clearly something else wrong.
The parseInt() function parses a string and returns an integer. The signature is
parseInt(string, radix) with
- string (required) being the string to be parsed, and
- radix (optional) a number (from 2 to 36) that represents the numeral system to be used
- If the string begins with “0x”, the radix is 16 (hexadecimal)
- If the string begins with “0”, the radix is 8 (octal)
- If the string begins with any other value, the radix is 10 (decimal)
PS.: Only the first number in the string is returned!
PPS.: Leading and trailing spaces are allowed.
PPPS.: If the first character cannot be converted to a number, parseInt() returns NaN.