Becky
Becky

Reputation: 5585

Using two arrays in for loop

I've got 2 arrays. both are text fields. I want to make textfield2 clear up when a keyup is triggered on textField1. how can I use both arrays in a keyup function?

var showItem=['orange', 'beans', 'rose'];
var typeItem=['fruit', 'veggie', 'flower'];

I tried using a for loop but does not work as expected.

for (i = 0; i < showItem.length; i++) {
    $('#' + showItem[i]).keyup(function () {
        console.log(typeItem[i]);
        $('#' + typeItem[i]).text('');
    });
}

Upvotes: 3

Views: 78

Answers (2)

Shashank
Shashank

Reputation: 13869

The issue is that all of the callbacks refer to a single variable i which is changing over time as you iterate through the array.

Instead of using a for-loop to iterate, you can elegantly use Array.prototype.forEach as an excuse to create separate closures for each of the callbacks. Then each inner function will have a reference to its own i value which will be effectively constant.

showItem.forEach(function(item, i) {
    $('#'+item).keyup(function(){
        $('#'+typeItem[i]).text('');
    });
});

Upvotes: 1

Tushar
Tushar

Reputation: 87203

Problem:

Value of i at the time when event is fired is 4 and there is no item at fourth index in both arrays, so $('#'+typeItem[i]).text(''); will not work.

Solution:

The code can be wrapped in IIFE and i can be passed to it, so that it'll be cached for each element. However, there's a better solution.

Use Array#indexOf to get the index of the clicked element.

var showItem = ['orange', 'beans', 'rose'];
var typeItem = ['fruit', 'veggie', 'flower'];

var selector = '#' + showItem.join(', #'); // '#orange, #beans, #rose'

$(selector).keyup(function () {
    // Get index of the id of the clicked element from array
    var index = showItem.indexOf($(this).attr('id'));

    // Get the element at index from second array and set the innerText to empty string
    $('#' + typeItem[index]).text('');
});

Upvotes: 2

Related Questions