0

I'm trying to dynamically bind click listeners to divs in a for loop.

If the second jQuery selector doesn't have + i, but is hard coded, then it works, like so:

eval(jQuery('#patient_name' + i).on('click touchstart', function(){jQuery('#taskstat0').slideToggle();}));

I also tried using two evals in the line like this:

eval(jQuery('#patient_name' + i)).on('click touchstart', function(){eval(jQuery('#taskstat' + i)).slideToggle();});

Yet this fails without console errors:

jQuery(document).ready(function(){
    var patient_count = jQuery('.patient_dropdown').length;
    for(var i=0; i<patient_count; i++){
        eval(jQuery('#patient_name' + i).on('click touchstart', function(){jQuery('#taskstat0').slideToggle();}));
    }
});

I expect each #patient_namex to show the corresponding #taskstatx div underneath when clicked.

What can be done to make it work?

Vörös Imi
  • 319
  • 4
  • 9
  • 1
    You don't need eval. Your root issue is the scope of the `i`. You need to use a closure. – Taplar Jan 14 '19 at 17:48
  • Thank you @Taplar for pointing it out! – Vörös Imi Jan 14 '19 at 17:52
  • Use something like `jQuery('.patient_dropdown').on('click touchstart', function () { $(this).next().slideToggle(); });` or another way of selecting the appropriate element based on the clicked one. –  Jan 14 '19 at 17:52

0 Answers0