1

I have a text box that should take only float value. It should not allow any other value. How to do it. I did this in HTML.

<h1>Weight</h1>
            <input class="textbox" type="number" step="0.01" name="weight" id="weight"
                 maxlength="5"></input>

But, it is not Working? How to do it.

Nikhil Kumar
  • 2,618
  • 3
  • 21
  • 24
  • This will help you out -> [How to allow only numeric (0-9) in HTML inputbox using jQuery?](http://stackoverflow.com/a/995193/1407478) `type="number"` does not itself prevent none-number characters, it does only provide spin buttons, in _some_ browsers. Though the suggested link targets jQuery, it iis easy to implement in plain javascript. – davidkonrad Mar 24 '15 at 07:43
  • possible duplicate of [allowing input only for float number](http://stackoverflow.com/questions/10150877/allowing-input-only-for-float-number) – NullPoiиteя Mar 24 '15 at 07:45
  • also helpful http://stackoverflow.com/questions/12467542/how-can-i-check-if-a-string-is-a-float – NullPoiиteя Mar 24 '15 at 07:45
  • http://stackoverflow.com/questions/6421639/jquery-only-allow-input-float-number"> Dublicate – ozil Mar 24 '15 at 07:47

1 Answers1

0
// remove whitespaces
var input = input.replace(/\s+/g,"");

// check if the input is a valid number
if(isFinite(input) && input != ''){
  // do your thing
}

Remember that isFinite only accepts values like '20.50' and not '20,50'.
the check for an empty string is necessary since isFinite('') returns true.

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}
Vikrant
  • 4,920
  • 17
  • 48
  • 72