Using the jQuery each() function to loop through classname elements
73,477
Solution 1
jQuery('.calculate').each(function() {
var currentElement = $(this);
var value = currentElement.val(); // if it is an input/select/textarea field
// TODO: do something with the value
});
and if you wanted to get its index in the collection:
jQuery('.calculate').each(function(index, currentElement) {
...
});
Reference: .each()
and .val()
functions.
Solution 2
$('.calculate').each(function(index, element) {
$(this).text()
});
Related videos on Youtube
Author by
Brett
Updated on September 08, 2020Comments
-
Brett almost 4 years
I am trying to use jQuery to loop through a list of elements that have the same classname & extract their values.
I have this..
function calculate() { // Fix jQuery conflicts jQuery.noConflict(); jQuery(document).ready(function(){ // Get all items with the calculate className var items = jQuery('.calculate'); }); }
I was reading up on the each() function though got confused how to use it properly in this instance.
-
Brett over 13 yearsThanks very much!! This may be a stupid question, but what does "it's index mean"?
-
Darin Dimitrov over 13 yearsIt's the index in the collection. So for example if you have 3 elements that match the selector this variable will increment on each iteration et and it will represent the index of the current element.
-
Albert Català over 10 yearsOne correction, with Rails and jquery-rails (3.1.0) the parameters are first index and then currentElemnt:
jQuery('.calculate').each(function(index,currentElement) ..
-
SearchForKnowledge over 9 yearsSomething I can use: stackoverflow.com/questions/27277272/… ?
-
xKobalt almost 4 yearsThis answer is not aligned with question:
$('.editable')
is neither declared in the question, nor in the answer