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?
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.
. 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.
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.
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.
don't think you need quotations on this:
var child = $("this");
try:
var child = $(this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With