0

Is there a way to turn this into a for loop? I have to run this code 114 time and am looking for a way to simplify this. The numbers on the class name would be the variable. The next one would be .select3 etc...

$('.select2').click(function () {
        if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic)
            {
                $(this).parent().clone().appendTo('.saved_list ul');
                $('.saved .select2').replaceWith('<div class="remove2">Remove</div>');
                $('.saved a').contents().unwrap(); 
            } else {
                alert ('You can only choose 3 paintings');  
            }
            if ($('.saved_list li').has('.thumb2')) {
                $(".select2 .img-swap").attr("src", "images/check_on.gif");
            } else {
                $(".select2 .img-swap").attr("src", "images/check_off.gif");
        };
    });
2
  • no need for a loop.. just make it more flexible.. show your html Commented Sep 18, 2012 at 1:53
  • Wouldn't it be easier to give them all a common class name, then you could just use a single selector for all of them? Commented Sep 18, 2012 at 1:54

2 Answers 2

2

Try this:

var run_select = function(index){
    var selector = '.select'+index;
    $(selector).click(function () {
        if ($('.saved_list .thumb2').length == 0 && $('.saved > li').length < totalPic)
        {
            $(this).parent().clone().appendTo('.saved_list ul');
            $('.saved '+selector).replaceWith('<div class="remove2">Remove</div>');
            $('.saved a').contents().unwrap(); 
        } else {
            alert ('You can only choose 3 paintings');  
        }
        if ($('.saved_list li').has('.thumb2')) {
            $(selector+" .img-swap").attr("src", "images/check_on.gif");
        } else {
            $(selector+" .img-swap").attr("src", "images/check_off.gif");
        };
    });
};
var i, l = 114;
for(i=1;i<=114;i++){
    run_select(i);
}
Sign up to request clarification or add additional context in comments.

Comments

-1

First, simplify html if you can. Use id for unique identifiers and the same name for css classes. Like this:

<div id='select2' class='select'></div>

Then use .each() if you want to get all your items:

$('.select').each(function() {
    // use $(this) here to refer to the current item
});

But in your case, you can simply apply the 'click' event like this:

$('.select').click(function(e) {
       // use $(this) or $(e.target) here to refer to the current item
       // if you need to get the id number you could get it from the id
       // (supposing has id='select2')

       var id = $(this).attr('id').substring(6); // it returns 2
});

Comments

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.