jQuery Form Selectors

Posted in Javascript -

There are a number of different <input> types in HTML and jQuery makes it simple to select the different types of input elements, such as all the text fields, all the radio buttons, all the submit buttons and so on. Full information and examples can be found on the selectors page of the jQuery document; this post gives some examples and a summary of the possible selectors.

Examples

The first example will match all the text type fields in a document:

$(':text')

To target a specific form use the following instead:

$('#myform :text')

Using a form id as in this second example also speeds up the selector because it does not have to scan the entire DOM to find all text inputs in the document.

To iterate through all the text fields and do something to them:

$('#myform :text').each(function() {
    // do something here
});

Substitute .each() for a different function depending on what is required.

Summary of selectors

$(':input') matches all input and textarea fields.

$(':text') matches all text type fields.

$(':password') matches all password fields.

$(':radio') matches all radio buttons.

$(':checkbox') matches all checkboxes.

$(':submit') matches all submit buttons.

$(':image') matches all image type inputs.

$(':reset') matches all reset buttons.

$(':button') matches all input buttons with the type button.

$(':file') matches all file upload fields.



Related posts:


Comments