JavaScript

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());
});
jQuery('#nameOfDiv').submit();

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.

2 Responses

  1. Irish

    August 21, 2014

    AKAIK youv’e got the answer in one!

    Reply
  2. Ewald

    August 18, 2015

    Excellent!

    I really had trouble with this and your solution is just what I need.

    Thank you for sharing.

    Reply

Leave a Reply