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


  • 2 Answer(s)

    We have to write a code that creates multiple DIVS according to the user data.Each div generate click option box and as per the user selected option data is displayed in it. now we want to set a id to the dynamic DIVS which is created using for loop. so we can access each DIVS Separately.Then
    we have used .id set DOM property but it is also not working.  we have saw some of the examples on Stackoverflow but that are in PHP language and
    it must be in JAVASCRIPT and HTML.

    Answered on May 3, 2019.
    Add Comment

    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.