views:

535

answers:

4

Ok what i'm trying to do is to count all of the elements in the current page with the same class and then i'm going to use it to be added onto a name for a input form. Basically i'm allowing users to click on an and then by doing so add another one for more of the same type of items. But i can't think of a way to count all of these simply with jquery/javascript.

I was going to then name the item as something like name="whatever(total+1)", if anyone has a simple way to do this i'd be extremely grateful as javascript isn't exactly my native tongue and stack overflow usually has a ton of great answers and a great community so i'm hoping my query will not go unheard.

+4  A: 

Should just be something like:

// Gets the number of elements with class yourClass
var numItems = $('.yourclass').length
PatrikAkerstrand
+2  A: 
var count = $('.' + myclassname).length;
Max Shawabkeh
A: 

for counting:

$('.yourClass').length;

should work fine.

storing in a variable is as easy as:

var count = $('.yourClass').length;

Alastair Pitts
+1  A: 

Getting a count of the number of elements that refer to the same class is as simple as this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"&gt;&lt;/script&gt;
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>
Jonathan