Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Dynamically assign onclick event in the loop

I have very simple html page with js code:

<html>
    <head>
        <title></title>
    </head>
    <body>

        <div id="divButtons">

        </div>

        <script type="text/javascript">
            var arrOptions = new Array();

            for (var i = 0; i < 10; i++) {
                arrOptions[i] = "option" + i;
            }

            for (var i = 0; i < arrOptions.length; i++) {
                var btnShow = document.createElement("input");
                btnShow.setAttribute("type", "button");
                btnShow.value = "Show Me Option";
                var optionPar = arrOptions[i];
                btnShow.onclick = function() {
                    showParam(optionPar);
                }

                document.getElementById('divButtons').appendChild(btnShow);
            }

            function showParam(value) {
                alert(value);
            }        
        </script>
    </body>
</html>

That page binds 10 buttons, but when you click on any button it always shows alert "option9". How is it possible assign onclick event to show correspondent option !?

Thanks!

like image 648
ihorko Avatar asked Feb 18 '11 10:02

ihorko


2 Answers

The accepted answer seems to work, but seems to be confusing and a somewhat cumbersome way to do it. A better way perhaps might be to use the data attribute for the element you're looking to assign the event listener for. It's simple, easy to understand, and way less code. Here's an example:

btnShow.data = arrOptions[i];

btnShow.onclick = function() {
  showParam(this.data);
}
like image 103
ray_voelker Avatar answered Sep 18 '22 12:09

ray_voelker


You'll have to do something like this:

btnShow.onclick = (function(opt) {
    return function() {
       showParam(opt);
    };
})(arrOptions[i]);
like image 44
Jacob Relkin Avatar answered Sep 16 '22 12:09

Jacob Relkin