How do i set id to dynamic div created using for loop in javascript and html

How do i set id to dynamic div created using for loop in javascript and html

Add Comment


  • 1 Answer(s)

    It’s happening because the AJAX callback handlers you create both share a reference to the same variable “i”. To avoid that, you can create your “success” handler with a separate function edit — in fact, due to the nature of your code structure here, you need to make the whole “change” callback in a separate function:

    function makeChangeHandler(listIndex) {
      return function() {
        var wdiv = $(this).val();
    
        $.ajax({
            type: "POST",
            url: "populate_classes.php",
            data: 'theOption=' + wdiv,
            success: function(whatigot) {
                $('#class_list' + listIndex).html(whatigot);
            } 
         });
      };
    }
    
    // ...
    
    for (var i = 0; i < 2; i++) { // for 2, substitute actual number of elements involved
        $('#wdiv' + i).change( makeChangeHandler(i) );
    }

     

    Answered on June 10, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.