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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks very much!! This may be a stupid question, but what does "it's index mean"?
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.
One correction, with Rails and jquery-rails (3.1.0) the parameters are first index and then currentElemnt: jQuery('.calculate').each(function(index,currentElement) ..
3
        $('.calculate').each(function(index, element) {
        $(this).text()
        });

1 Comment

This answer is not aligned with question: $('.editable') is neither declared in the question, nor in the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.