bobek
bobek

Reputation: 8022

jQuery looping through classes using each() - problem

I am using this code to loop through each ".accessoryrow" and then select "dialog" + counter and ".see-details" + counter. So first time when loop goes by it selects dialog1 class and see-details1 class; second time dialog2, see-details2 and so on. I think I am not correctly adding counter to the selector. Please correct me. Thank you

CODE:

  var counter = 1;
        $(function () {
        $(".accessoryrow").each(function() {
            $(".dialog" + counter).dialog({
                autoOpen: false,
                show: "blind",
                hide: "fade"
            });

            $(".see-details" + counter).click(function () {
                $(".dialog" + counter).dialog("open");
                return false;
            });
            counter++;
        });

Upvotes: 0

Views: 328

Answers (2)

Bobson
Bobson

Reputation: 13706

The problem is that the $(".dialog" + counter).dialog("open"); line isn't getting evaluated until the link is clicked. Thus it's using the value of counter which is current as of then. A better way to do it would be to take out the counter altogether, and use jQuery selectors to select the correct .dialog.

Without the HTML, I can't say what it should look like, but you're going to want the click function to look like something along the lines of

 $(".see-details").click(function () {
        $(this).sibling(".dialog").dialog("open");
        return false;
    });

Of course, that assumes that the .dialog element is actually a sibling of .see-details. You'll need to traverse the tree a bit more if it isn't.

Upvotes: 1

Robert
Robert

Reputation: 325

Try this (untested):

$(function () {
    $(".accessoryrow").each(function(index) {
        $(".dialog" + (index + 1)).dialog({
            autoOpen: false,
            show: "blind",
            hide: "fade"
        });

        $(".see-details" + (index + 1)).click(function () {
            $(".dialog" + (index + 1)).dialog("open");
            return false;
        });
    });

Index passes the loop number to the function. It starts from 0, where I think you need it to start at 1, so I've added 1 to each where it's used.

Upvotes: 0

Related Questions