Reputation: 55
I've got multiple elements on .list1 and .list2 uls, .list2 is not visible and elements from .list1 triggers elements from .list2. I do not know how many elements there will be so I would like to use loop for some jQuery code with click event. But the loops does not work. What am I doing wrong?
<ul class="list1">
<li class="opt1">option1</li>
<li class="opt2">option2</li>
<li class="opt3">option3</li>
<li class="opt4">option4</li>
<li class="opt5">option5</li>
<ul class="list2">
<li class="opt1">option1</li>
<li class="opt2">option2</li>
<li class="opt3">option3</li>
<li class="opt4">option4</li>
<li class="opt5">option5</li>
for (var x = 1; x <= 5; x++){
$(".list1 li.opt" + x).click(function() {
$(".list2 li").removeClass("selected");
$(".list2 li.opt" + x).addClass("selected");
});
}
Upvotes: 0
Views: 586
Reputation: 67207
Try to write a single event
for this purpose do not go for a for
loop, and make use of the .index()
to grab the related element from list-2
$('.list1 li').click(function () {
$('.list2 li').removeClass("selected").eq($(this).index()).addClass("selected");
});
Upvotes: 2