jQuery: Iterate Through a Form’s Elements CodeUnit 04 NOV 2009

jQuery-logoTo iterate though a web form’s contents using jQuery is as easy as 123. First, make use of the $(‘:input’) selector and force it to grab the contents of a particular form by extending the selector with $(‘:input’, ‘#yourFormID’) where yourFormID is obviously the ID of the form you are interested in iterating through.

The next step is to make use of the each function to iterate through the selector’s returned array and using the this keyword, you should now be good to go.

The example below simply iterates through a form’s contents and spits out an alert detailing the input’s name and current value. (Note that for radio buttons you will need to take the inputs tagName value into consideration in order to figure out which radio button is currently selected.) 

$(document).ready(function() {
    $('#yourButtonID').click(function () {
        $(':input', '#yourFormID').each(function() {
            alert(this.name + ': ' + this.value);
        });
    });
});

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.