1

When this initially loads employmentJobs displays as employmentJobs1 in the console which is what I want. Once I clicked on the button which has the .employmentJobs1 .addDuty class it should log out employmentJobs1 again but instead it logs out employmentJobs2.

Could anyone provide any guidance?

for (var q = 1; q <= 1; q++){
   console.log('employmentJobs'+q); 

    $('.employmentJobs'+q +' .addDuty').click(function(){

        console.log('employmentJobs'+q); 
        countDuties++;
        $('.employmentJobs'+q +' .mainDuties').clone().attr('class', 'form-group mainDutyOrder mainDuties'+ countDuties).insertAfter('.employmentJobs'+q +' .mainDutyOrder:last');

        return false;

    }); 

  }
}
1
  • 3
    Why are you putting a click handler within a loop? Commented Jan 20, 2016 at 17:50

2 Answers 2

4

The function in your click event handler executes at a far later time, meaning that the loop has finished (and the value of q as a result is the final value of the loop in every click event). Simply close over the value of q using an IIFE to create a new execution context.

for (var q = 1; q <= 1; q++){

   //close over q
   (function(q){

   console.log('employmentJobs'+q); 

    $('.employmentJobs'+q +' .addDuty').click(function(){

        console.log('employmentJobs'+q); 
        countDuties++;
        $('.employmentJobs'+q +' .mainDuties').clone().attr('class', 'form-group mainDutyOrder mainDuties'+ countDuties).insertAfter('.employmentJobs'+q +' .mainDutyOrder:last');

        return false;

    }); 

  //pass q in to close over its value
  })(q)

}
Sign up to request clarification or add additional context in comments.

Comments

0

Despite the fact, that you should NOT put event bindings in loops, your problem tackles "encapsulation".

JavaScript uses a so called function scope. But what you need is a block scope(i.e. c#).

Here you can find an exact description of this kind of problem and there are even examples that exactly fit your needs.

But what you could instead also do is: put your elemets in containers, and bind a click dynamically on them like:

$('body).on('click', '.yourWrapperElement > .clickableElements', function() {
    //cour cloning magic here
});

this makes all children inside .element clickable, even if they're added after the document is loaded

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.