Ekso
Ekso

Reputation: 5

jQuery multiple variables in for loops

This might be simple thing but just can't figure it out.

Let's assume I got fifty similar functions and there's two of them:

var unit = ['red', 'pink']
var unit2 = ['red2', 'red2']

$('#red').click(function() {
if($('#red2').is(':hidden')) {
$('#red2').toggle();
} else {
$('#red2').toggle();}}}

and

$('#pink').click(function() {
if($('#pink2').is(':hidden')) {
$('#pink2').toggle();
} else {
$('#pink').toggle();}}}

and I want to add all these functions in one/two for loops. I tried this:

for (var i = 0; i < unit.length; i++) {
for (var y = 0; y < unit2.length; y++) {
$('#i').click(function() {
if($('#y').is(':hidden')) {
$('#y').toggle();
} else {
$('#y').toggle();}}}}

Upvotes: 0

Views: 1044

Answers (2)

Alex
Alex

Reputation: 1593

You should concatenate strings:

for (var i = 0; i < unit.length; i++) {
  $('#' + unit[i])
  .attr('data-dst', unit2[i])
  .click(function() {
    var dst = $(this).attr('data-dst');
    $('#' + dst).toogle();
  }
}

Upvotes: 0

Ram
Ram

Reputation: 144669

.toggle() method detects the visibility of the element itself, there is no need to use if statement, you can use this keyword which refers to the clicked element:

$('#red, #pink').on('click', function() {
   // Based on the id property of the clicked element 
   // this selects #red2 or #pink2 element
   $('#' + this.id + '2').toggle();
});

Also note that $('#i') selects an element with ID of i, you should concatenate the strings:

$('#' + i).foo();

Upvotes: 2

Related Questions