Reputation: 439
I have the following code where I am able to loop through all my form fields but the value is getting saved only for the first one and due to this the console shows 7 iterations of the first form field value only.On the other hand I want it to come one by one for all the form fields so that I can validate them. Thanks in advance.
$('formsection[name="AUDIT REPORT"]').find('input,select').each(function() {
hi = [];
hi = $('formsection[name="AUDIT REPORT"]').find('input,select').val();
console.log(hi);
});
Upvotes: 1
Views: 603
Reputation: 337560
Firstly note there should be a space between form
and section
in the selector, as formsection
isn't a valid HTML element.
The issue itself is due to the use of the same selector within the each()
handler function. As the resulting jQuery object contains a collection of Elements then calling val()
will only read from the first element of the set. It does not return an array as you seem to be expecting.
To fix this, use the this
keyword to refer to the current element in the iteration:
$('form section[name="AUDIT REPORT"]').find('input,select').each(function() {
var hi = $(this).val();
console.log(hi);
});
Also note that the :input
selector could also meet your needs without the use of find()
:
$('form section[name="AUDIT REPORT"] :input').each(function() {
var hi = $(this).val();
console.log(hi);
});
Upvotes: 2