Alex Rivera | Logout

Looping over elements in jQuery

Asked 2008-10-04T11:39:25.497
27

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?

Edit
Report

1 Answer

0

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

$("#formID input[type=text]").each(function() {
alert($(this).val());
});
answered 2013-01-16T05:10:54.883

Your Answer