each method in jQuery with example




1. each() method is used to iterate over both arrays and objects.
2. $.each() function is different from $(selector).each(), which is used to iterate exclusively over jQuery object.
3. $.each() function can be used to iterate over any object, whether it is javascript object or an array.


Example 1 :



        <html>
        <head>
        <title>each</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myButton").click(function () {
                    $(".eachDiv").each(function (i) {
                        $(this).append("Div " + i);
                    });
                });
            });
        </script>
        </head>
        <body>
        <div class="eachDiv">This is </div>
        <div class="eachDiv">This is </div>
        <div class="eachDiv">This is </div>
        <div class="eachDiv">This is </div>
        <input type="button" id="myButton" value="Click ME"/>
        </body>
        </html>
Demo :




In above example, we have created 4 div elements. Using class selector we are selecting all div's in an jquery object. Using each object, we are iterating over each div and printing the text and index.



Example 2 :



        <html>
        <head>
        <title>checked Selector</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> 
        </script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#myButton").click(function () {
                    var text = "";
                    $(":Checked").each(function () {
                        text = text + "   " + $(this).val();
                    });
                    var spanText = $("#checkedSpan").html();
                    if (spanText != null) {
                        $("#checkedSpan").innerHTML = " ";
                    }
                    $("#checkedSpan").html("You selected: " + text);
                });
            });
        </script>
        </head>
        <body>
        <input type="checkbox" name="BE" value="BE">BE
        <input type="checkbox" name="ME" value="ME">ME
        <input type="checkbox" name="MS" value="MS">MS
        <input type="checkbox" name="MCA" value="MCA">MCA
        <button id="myButton">Click</button><br>
        <span id="checkedSpan"></span>
        </body>
        </html>
    



In above example, we have rendered 4 checkboxes. And on checking more than one checkbox, we are using checked selector to select all checked checkboxes and used each() method to iterate through each checked checkbox and displaying the result.


1 comments: