1

I have created this example where i am trying to set on click event for dynamically created div, but i am not able to get the parameter value which passing while setting click event. In this example i have used array but in reality i am getting json by web service.

$(document).ready(function () {
    myfunction();
});

function myfunction() {
    var cars = ["Saab", "Volvo", "BMW"];


    for (var i = 0; i < cars.length; i++) {
        $('<div/>', {
            id: 'pnlmyDiv_' + i,
            html: '<b>Click Me ' + i + '</b><br>',
            style: 'padding:10px;border-width:1px;border-style:solid;margin-bottom:5px;cursor:pointer;'
        }).appendTo('#pnlParent');


        $("#pnlmyDiv_" + i).on("click", function () {
            fnGetMessages(cars[i])
        });
    }


}

function fnGetMessages(car) {
    alert(car);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="pnlParent" style="padding:5px;border:solid">
</div>
Erazihel
  • 7,295
  • 6
  • 30
  • 53
SAURABH
  • 135
  • 1
  • 1
  • 11
  • Use a closure (as in the duplicate I linked) or alternatively use a single delegated event handler and put custom metadata in `data` attributes on the elements you append to the DOM. Personally, I'd use the latter – Rory McCrossan Jul 18 '17 at 08:36

1 Answers1

2

Try this code:

$(document).ready(function () {
        myfunction();
    });

    function myfunction() {
        var cars = ["Saab", "Volvo", "BMW"];


        for (let i = 0; i < cars.length; i++) {
           jQuery('<div/>', {
        id:  'pnlmyDiv_' + i,
        html: '<b>Click Me ' + i + '</b><br>',
         style: 'padding:10px;border-width:1px;border-style:solid;margin-bottom:5px;cursor:pointer;'
           
        }).appendTo('#pnlParent');


            $("#pnlmyDiv_" + i).on("click", function () {
                fnGetMessages(cars[i])
            });
        }


    }

    function fnGetMessages(car) {
        alert(car);
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="pnlParent" style="padding:5px;border:solid; height:150px;">
</div>
N.Malloul
  • 223
  • 2
  • 14