loop through input elements

Loop through Input Elements in a DIV Tag with jQuery

Posted on: February 26th, 2014 by taff 2 Comments


Occasionally you need to loop through input elements prior to submission so that you can see what exactly is being submitted.
I like to use jQuery, the javascript framework of my choice for this. Although the title describes looping through input elements in a DIV Tag, you can use the following script to equally loop through elements in a FORM tag identically.

The following script will loop through input elements in the DIV tag with the ID nameOfDiv. You can, of course, use a different selector if you need the elements in multiple divs.

var $inputs = jQuery('#nameOfDiv :input');
var values = {};
$inputs.each(function() {
    console.log(values[this.name] = jQuery(this).val());

Using the jQuery each function we can loop through all the input elements in our div. For the example, I am simply outputting them into the console window, i.e. Firebug or the Chrome console.