06 – Form filters in jQuery

Many times you need to select elements that are part of a form. For example you might want to select all check-boxes that are selected.

You could match by attribute $('input[type="checkbox"][checked]'); but that will match only the initial state (specified in HTML markup).

What you want to do is to check its state in real time. For that you have to use the CSS pseudo-class :checked. This pseudo-class matches all the elements that are in the checked state. So, you should write something like shown below:

$('input[type="checkbox"]:checked');

You may also want to combine the custom jQuery selector :checkbox with the CSS pseudo-class :checked to create a very powerful custom filter.

$('input:checkbox:checked');

Here you have a list of CSS filter selectors supported by jQuery and a few custom selectors.

  • :button – Selects only button elements
  • :checkbox – Selects only check box elements
  • :checked – Selects check boxes / radio elements in the checked state (or options of select elements that are in a selected state)
  • :disabled – Selects only elements in the disabled state
  • :enabled – Selects only elements in the enabled state
  • :file – Selects only file input elements (input[type=file])
  • :focus – Selects elements that have the focus at the time the selector is run
  • :image – Selects only image input elements (input[type=image])
  • :input – Selects only form elements (input, select, textarea, button)
  • :password – Selects only password elements (input[type=password])
  • :radio – Selects only radio elements (input[type=radio])
  • :reset – Selects only reset buttons (input[type=reset] or button[type=reset])
  • :selected – Selects only option elements that are in the selected state
  • :submit – Selects only submit buttons (button[type=submit] or input[type=submit])
  • :text – Selects only text elements (input[type=text]) or input without a type specified (type=text is the default)

Note:
The CSS and custom jQuery filter selectors can be combined.

Leave a Reply