April 19, 2012

How to get all input fields which aren't selects

Question by Hard worker

var $inputs = $('.add-item-form :input');

This gets all the input fields but also picks up the select fields which I do not want.

e.g.

<select><option>example</option></select>

Answer by T.J. Crowder

:input is a jQuery-specific pseudo-selector for input, textarea, button, and select elements. So you could do this:

var $inputs = $('.add-item-form :input:not(select)');

…but you can also just call out specifically what you want:

var $inputs = $('.add-item-form input, .add-item-form textarea, .add-item-form button');

…which would have the advantage that if the browser supports querySelectorAll (and nearly all do, in standards mode), jQuery can just hand off to native handling (whereas :input is specific to jQuery, so can’t be handled by the browser’s native stuff).

Or, of course, if you don’t want textarea and button elements, it’s really simple:

var $inputs = $('.add-item-form input');

…and again that has the advantage of being handled by the browser’s optimized stuff where possible.

Answer by Starx

Use a .not() to omit the select boxes

var $inputs = $('.add-item-form :input').not("select")

Or use CSS style :not selector

var $inputs = $('.add-item-form :input:not(select)');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!