26

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.

GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Brett
  • 19,449
  • 54
  • 157
  • 290

2 Answers2

78
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.

Thomas G Henry LLC
  • 10,887
  • 8
  • 30
  • 32
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks very much!! This may be a stupid question, but what does "it's index mean"? – Brett Mar 13 '11 at 20:22
  • 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. – Darin Dimitrov Mar 13 '11 at 20:24
  • 1
    One correction, with Rails and jquery-rails (3.1.0) the parameters are first index and then currentElemnt: `jQuery('.calculate').each(function(index,currentElement) ..` – Albert Català Feb 06 '14 at 19:30
  • Something I can use: http://stackoverflow.com/questions/27277272/how-to-emulate-xslt-using-jquery-from-html-source ? – SearchForKnowledge Dec 03 '14 at 17:03
3
        $('.calculate').each(function(index, element) {
        $(this).text()
        });
Ashish Mishra
  • 412
  • 4
  • 5
  • This answer is not aligned with question: `$('.editable')` is neither declared in the question, nor in the answer – xKobalt Sep 07 '20 at 14:33