Using the jQuery each() function to loop through classname elements
Asked Answered
D

2

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.

Detestable answered 13/3, 2011 at 20:10 Comment(0)
C
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.

Conquer answered 13/3, 2011 at 20:11 Comment(4)
Thanks very much!! This may be a stupid question, but what does "it's index mean"?Detestable
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.Conquer
One correction, with Rails and jquery-rails (3.1.0) the parameters are first index and then currentElemnt: jQuery('.calculate').each(function(index,currentElement) ..Wahoo
Something I can use: #27277772 ?Divorce
U
3
        $('.calculate').each(function(index, element) {
        $(this).text()
        });
Unsure answered 7/9, 2020 at 13:2 Comment(1)
This answer is not aligned with question: $('.editable') is neither declared in the question, nor in the answerBine

© 2022 - 2024 — McMap. All rights reserved.