T.G
T.G

Reputation: 1921

jQuery validating input type number

I'm trying to set function onFocusOut event with jQuery like:

$(':number').keypress(function (evt){
    //validating cone
}

but it can't select number types throwing an error

Error: Syntax error, unrecognized expression: number

Same code for type text works fine.

Does jQuery not know a number datatype? How to make it work?

Upvotes: 1

Views: 4467

Answers (2)

Alexander
Alexander

Reputation: 23537

For the record, you can extend jQuery to add a custom :number selector.

$.expr[':']​​​​.number = function(elem){
  return $(elem).is("input[type='number']");
}​;

Or pure javascript.

$.expr[':']​​​​.number = function(elem){
  return (elem.tagName === "INPUT") &&
         elem.getAttribute("type") &&
         (elem.getAttribute("type").toUpperCase() === "NUMBER");
}​;

Upvotes: 1

Phil
Phil

Reputation: 1308

Are you trying to select <input> elements with the number as the type? Try this:

$('input[type="number"]').keypress(function (evt){

}

Upvotes: 5

Related Questions