Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery val refuses to return non numeric input from a number field (Under Chrome)

Just stumbled across something weird in jQuery, while writing some validation code- I have an html5 "number" field;

<input type="number" class="required numeric" />

My script will then look at every field on the page checking out the classes and validating as needed. I noticed weirdly that if i enter an 'X' into one of my numeric fields i get a "Please enter a value into this field" error instead of a "this should be a number" error. After some head scratching and a lot of debugging I knocked up a jsFiddle to demo my theory- it appears if you enter a character into a number field, then try to do a .val() from jquery it will return nothing- as though the field was empty (I came across this in Chrome- not sure if it works like this across all the browsers);

http://jsfiddle.net/shawson/SE46L/3/

Here's the fiddle- enter some numbers, then a few letters to see the crazyness. Anyone know if this is by design, and if so... why?

like image 723
Shawson Avatar asked May 07 '13 13:05

Shawson


People also ask

How do you make an input only accept the number?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

Is number validation in jQuery?

The jQuery $. isNumeric() method is used to check whether the entered number is numeric or not. $. isNumeric() method: It is used to check whether the given argument is a numeric value or not.

How do I restrict only numbers in a text box in HTML?

You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.


1 Answers

This is not a jQuery issue. You will get the same result if you use the native element.value (e.g. with getElementByID('something').value). It's quirk of how Chrome deals with input type=number and you can choose to work around it by using type=text and the pattern property.

See this older question for more background.

like image 165
explunit Avatar answered Sep 25 '22 07:09

explunit