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()
        });
Share:
73,477

Related videos on Youtube

Brett
Author by

Brett

Updated on September 08, 2020

Comments

  • Brett
    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
    Brett over 13 years
    Thanks very much!! This may be a stupid question, but what does "it's index mean"?
  • Darin Dimitrov
    Darin Dimitrov over 13 years
    It'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à
    Albert Català over 10 years
    One correction, with Rails and jquery-rails (3.1.0) the parameters are first index and then currentElemnt: jQuery('.calculate').each(function(index,currentElement) ..
  • SearchForKnowledge
    SearchForKnowledge over 9 years
  • xKobalt
    xKobalt almost 4 years
    This answer is not aligned with question: $('.editable') is neither declared in the question, nor in the answer