1

I am trying to get array elements(which may be objects) in alert onclick. But, message is not binding on click.

this.openLink() method not getting alert for message and correct value.

I am missing something here while binding click events?

<!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script> 

     function myBox(){

     this.create = (id, id3 , arrData) => {
     var html = "<div id='box1' class='col-12'></div>";
     $("#box").append(html);
      var html1 = "<div id='box2' class='col-12'></div>";
     $("#box").append(html1);
     this.createList(id, id3 , arrData)

     }

     this.createList = (id, id3 , arrData) =>{
     var html = '';
         html +='<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style-                 type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
          for (var i = 0; i < arrData.length; i++) {
             var iD = id + '_utt' + i;
          html += '<li  id="' + iD + '"   class="col-12 rmpm" style="display:inline;width:auto;border:1px solid         #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
          html += arrData[i];
          html += '</li>';
        }
          html += '</ul>';
          $(id3).append(html);

// ---> here, some error for binding click event on li

          arrData.forEach((element) => {
            $(document).on('click', '#' + iD, () => {
              this.openLink(element);
            });
        });
     }

     this.openLink = (message) =>{
      alert(message); //a,b,c,as,bqsq,csqs  <--- alert expecting here
     }
     }


    </script> 
    <script>
    function abc(){
      var  arrData = ['a','b','c'];
      var arrData2 = ['as','bqsq','csqs'];
     var bx = new myBox();
       bx.create('arrData',"#box1" , arrData);
         bx.create('arrData2',"#box2" , arrData2);
    }

    </script> 
    </head>
    <body>
    <button onclick="abc()">Clcik</button>
    <div id="box" style=""></div>

    </body>
    </html>
2
  • Do you receive any errors in your browsers console? Commented Mar 9, 2019 at 21:13
  • No, but the click event is happening for 'c' and 'csqs' only not for other values in li and it is causing 3 alerts continuosly. Commented Mar 9, 2019 at 21:14

1 Answer 1

2

You are assembling the id, in the for loop above your foreach, then you are using that id to set the clicklistener, you need to assemble the correct id at every loop in the foreach or else you will only put a listener on the last button.

Change your forEach to this:

arrData.forEach((element, index) => {
var clickId = id + '_utt' + index;
  $(document).on('click', '#' + clickId, () => {
    this.openLink(element);
  });
});

To put it into the html as an onclick="function()" you need to assign it in the first loop when you are creating the HTML. and move openlink outside myBox()

function myBox() {

  this.create = (id, id3, arrData) => {
    var html = "<div id='box1' class='col-12'></div>";
    $("#box").append(html);
    var html1 = "<div id='box2' class='col-12'></div>";
    $("#box").append(html1);
    this.createList(id, id3, arrData)

  }

  this.createList = (id, id3, arrData) => {
    var html = '';
    html += '<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style-                 type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
    for (var i = 0; i < arrData.length; i++) {
      var iD = id + '_utt' + i;
      html += '<li ' + 'onclick="openLink(\'' + arrData[i] + '\')" id="' + iD + '"   class="col-12 rmpm" style="display:inline;width:auto;border:1px solid         #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
      html += arrData[i];
      html += '</li>';
    }
    html += '</ul>';
    $(id3).append(html);
  }
}

openLink = (message) => {
  alert(message); //a,b,c,as,bqsq,csqs  <--- alert expecting here
}

function abc() {
  var arrData = ['a', 'b', 'c'];
  var arrData2 = ['as', 'bqsq', 'csqs'];
  var bx = new myBox();
  bx.create('arrData', "#box1", arrData);
  bx.create('arrData2', "#box2", arrData2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<body>
  <button onclick="abc()">Clcik</button>
  <div id="box" style=""></div>
</body>

' + 'onclick="openLink(\'' + arrData[i] + '\')" . How does this worked. Can you please explain or provide some link so that I can understand

The line renders as onclick="openLink('a')" onclick="openLink( renders to the DOM as written. the \' renders a ' in the DOM and javascript sees it as a character that way i dont break the string, but it renders as a ' in the DOM. Then i add arrData[i] that is the n'th (or i'th) index in the array. then i use the same trick to close the onclick function off.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks, I missed it. But can we directly bind html += '<li id="' + iD + '" onclick="this.openLink(arrData[i])"></li> ; where element may be objects in array. If its possible, can you help.
var arrData = [ {"key1":"2"}, {"key1":"3"} ]; var arrData2 = [{"key1":"4"}, {"key1":"6"}]; openLink = (message) => { alert(JSON.stringify(message)); alert(message.key1); }
It fails for var arrData = [ {"key1":"2"}, {"key1":"3"} ]; var arrData2 = [{"key1":"4"}, {"key1":"6"}];
Yes because you now encoded your data in an object, so you need to call refer the key to get the value. [ {"key1":"2"}, {"key1":"3"} ] !== ["2", "3"]
What if we need to pass the object like { "id": "upctings", "utces": [ "Setupow at 9 pm" ], "api": "api/" } onclick. As we normally pass object in function call. How can we achieve this . However, we can pass object when we use bindings in forEach. Can you please guide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.