Monday, July 25, 2016

jQuery and forms

Selecting form controls with jQuery selectors

jQuery selector working with forms are not always the fastest option to select elements: when you use them remember to reduce the number of elements jQuery needs to look through. Orthewise, use common CSS selectors

Example of use of jQuery selectors for forms

/* to start, select all form descendants,
   then, use the filter() method on the initial selection */
var $formDescs = $('form *');

/* :input selects all button, input, select and textarea */
var $inputs = $formDescs.filter(':input');
/* :text selects input type="text" and input */  
var $text = $inputs.filter(':text'); 

/* :password selects input type="password" */
var $password = $inputs.filter(':password');   

/* :button selects button and input type='button' */
var $button = $inputs.filter(":button");  

/* :checked selects all checked inputs from group of radio and check inputs */
var checked = $inputs.filter(":checked");

/* :selected selects all selected options from drop boxes */
var selected = $inputs.filter(":selected"); 

Sometimes, you get the best results with common CSS selectors

/* use standard CSS selector for input type="radio" */
var $radio = $("[type='radio'][name='gender']");

/* use standard CSS selector for input type="checkbox" */
var $checkboxes = $("[type='checkbox']");

/* use standard CSS selector for input type="submit" and button type="submit"  */
var $submits = $("[type='submit']");

Example: using jQuery form selectors

See the Pen jQuery forms 1 (w/ bootstrap) by Massimiliano (@maxdesimone) on CodePen.

Example: using form events with jQuery

See the Pen jQuery forms by Massimiliano (@maxdesimone) on CodePen.

No comments :

Post a Comment