Reputation: 368
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;
});
}
}
Upvotes: 1
Views: 48
Reputation: 593
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
Upvotes: 0
Reputation: 82267
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)
}
Upvotes: 4