[javascript] Looping over elements in jQuery

I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though:

function config() {
    $("#frmMain").children().map(function() {
        var child = $("this");
        if (child.is(":checkbox"))
            this[child.attr("name")] = child.attr("checked");
        if (child.is(":radio, checked"))
            this[child.attr("name")] = child.val();
        if (child.is(":text"))
            this[child.attr("name")] = child.val();
        return null;
    });

Neither does the following (inspired by jobscry's answer):

function config() {
    $("#frmMain").children().each(function() {
        var child = $("this");
        alert(child.length);
        if (child.is(":checkbox")) {
            this[child.attr("name")] = child.attr("checked");
        }
        if (child.is(":radio, checked"))
            this[child.attr("name")] = child.val();
        if (child.is(":text"))
            this[child.attr("name")] = child.val();
    });
}

The alert always shows that child.length == 0. Manually selecting the elements works:

    
>>> $("#frmMain").children()
Object length=42
>>> $("#frmMain").children().filter(":checkbox")
Object length=3

Any hints on how to do the loop correctly?

This question is related to javascript jquery

The answer is


I have used the following before:

var my_form = $('#form-id');
var data = {};

$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
    function() {
        var name = $(this).attr('name');
        var val = $(this).val();

        if (!data.hasOwnProperty(name)) {
            data[name] = new Array;
        }

        data[name].push(val);
    }
);

This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).


jQuery has an excellent function for looping through a set of elements: .each()

$('#formId').children().each(
    function(){
        //access to form element via $(this)
    }
);

I have used the following before:

var my_form = $('#form-id');
var data = {};

$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
    function() {
        var name = $(this).attr('name');
        var val = $(this).val();

        if (!data.hasOwnProperty(name)) {
            data[name] = new Array;
        }

        data[name].push(val);
    }
);

This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.

Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.

Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).


Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...

$("#formID").serialize()

It creates a string for you with all of the values automatically.

As for looping through objects, you can also do this.

$.each($("input, select, textarea"), function(i,v) {
    var theTag = v.tagName;
    var theElement = $(v);
    var theValue = theElement.val();
});

This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.

EDIT JSFIDDLE

The below will work

$('form[name=formName]').find('input, textarea, select').each(function() {
    alert($(this).attr('name'));
});

for me all these didn't work. What worked for me was something really simple:

$("#formID input[type=text]").each(function() {
alert($(this).val());
});

if you want to use the each function, it should look like this:

$('#formId').children().each( 
  function(){
    //access to form element via $(this)
  }
);

Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time.