1

I am working with an array of selectors:

var selectors = ['#first_name', '#last_name'];

I want to be able to bind events such as focus, change, keyup, etc to each selector in that array. The selectors are attached to form inputs.

For binding each selector I have the following code.

for(var selector in selectors){
    $('#form').find(selectors[selector]).on('change keyup click select focus', function(){
    console.log(selectors[selector]); //this is here for testing
    });
}

This should logically work but when I read the console log it shows #last_name twice.

I have checked the form over and over, and it has nothing to do with the form. The only problem in my code is this single logic structure that I have provided. If I console log the array before the loop it shows the array as is ['#first_name', '#last_name'], so that is why I am so confused.

Mark Hill
  • 1,769
  • 2
  • 18
  • 33

1 Answers1

1

You can use comma separated selectors, there is no need for loop. The reason for firing twice in console is due to firing multiple objects on same time, that when you clicking in a new input it will fire click and focus event at same time.

$('#form').find(selectors.join()).on('change keyup click select focus', function(){
    console.log(this); //this is here for testing
});
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188