Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 218
Christian Aichinger Avatar asked Oct 04 '08 11:10

Christian Aichinger


People also ask

How do you loop through an element with the same class in jQuery?

Answer: Use the jQuery each() Method You can simply use the jQuery each() method to loop through elements with the same class and perform some action based on the specific condition.

How do you iterate in jQuery?

. each() is used directly on a jQuery collection. It iterates over each matched element in the collection and performs a callback on that object. The index of the current element within the collection is passed as an argument to the callback.

How do I iterate through a div in jQuery?

jQuery Selector can be used to find (select) HTML elements from the DOM. Once an element is selected, the jQuery children() method is called to find all the child elements of the selected element.

How do I traverse an array in jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.


1 Answers

don't think you need quotations on this:

var child = $("this"); 

try:

var child = $(this); 
like image 122
imjoevasquez Avatar answered Sep 18 '22 07:09

imjoevasquez