2

Is there a way using Jquery or just plain javascript that you can derive if something is a form field? Example

<div id='some_id'></div>

or:

<input type='text' id='some_id'>

Is there a way to check $('#some_id') to ensure it is actually a valid form field type like input, select, checkbox, radio, etc. and not a div, td or other element?

OneChillDude
  • 7,856
  • 10
  • 40
  • 79
Jafo
  • 1,200
  • 2
  • 11
  • 22

2 Answers2

9

jQuery has an :input selector that matches form fields (input, textarea, select, etc.)

$(el).is(':input')

Where el is a selector or a DOM element.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
3

You can use is() to find out the elements type :

if ( $('#some_id').is('input') ) {
    // it's an input element
}

if ( $('#some_id').is('div') ) {
   // it's a div
}

you can even check for multiple types :

$('#some_id').is('input, select, textarea, button');

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 2
    That won't match `textarea` or `select`. – SLaks Jun 11 '13 at 20:57
  • 1
    Why not change `input` to `:input`... – marteljn Jun 11 '13 at 20:58
  • 2
    @SLaks - Just add more elements to the selector then ? – adeneo Jun 11 '13 at 21:03
  • 1
    @marteljn - I just always try to stay away from jQuery's pseudo selectors as much as possible, and certainly in a selector without any context. – adeneo Jun 11 '13 at 21:05
  • Don't forget `button` :) – Ian Jun 11 '13 at 21:06
  • @marteljn And there's already an answer that uses that – Ian Jun 11 '13 at 21:07
  • Typo in your fiddle: please id=test2 is repeated twice, otherwise, it works fine. – Marc Audet Jun 11 '13 at 21:07
  • @ian, you could add anything I guess, but when you have to test what type your elements are, you probably should start rethinking something else. – adeneo Jun 11 '13 at 21:08
  • @adeneo Oh I agree, and I agree with your opinion about jQuery pseudo selectors. I was just saying, to more fulfill the OP's request to check `is a form field`, I thought `button` should be included...that's all...not crazy important :) – Ian Jun 11 '13 at 21:09
  • @Ian - yeah, some of those psuedo selectors can be really inefficient, and `:input` is no different. Not sure how it works when used with `is()`, if it just checks the elements type from a list of known form elements or what, if so, that's not so bad, but just doing `$(':input')` to get all form elements in the DOM is not something I'd use a lot? – adeneo Jun 11 '13 at 21:14
  • @adeneo I'm sure it's not as bad with `is()`, but it still has to be parsed (more than what a comma-separated string of tagnames would be). It looks like `is()` ends up internally using `.filter()` (and `.grep()`) for some reason, for strings. But yeah, in the docs, they suggest **always** selecting/filtering elements in some way before using a jQuery pseudo selector, because of its inefficiency. It's usually easy enough to not use, such as your example – Ian Jun 11 '13 at 21:21