3

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('');
    });
}
1
  • What happens when you run that code? You need to define better what "does not work as expected" means. Commented Nov 30, 2015 at 4:16

2 Answers 2

2

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('');
});
Sign up to request clarification or add additional context in comments.

Comments

1

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('');
    });
});

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.