0

I'm currently developing a chrome extension. and my chrome extension has a table with buttons on it. But unfortunately the my buttons won't work and there's no errors in the console..

My question is why my button id in my address.js "copy" wont triggered an alert

This is my home.html in my chrome extension

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"  rel="stylesheet">


    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

    <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" ></script>

<script type="text/javascript" src = "address.js"></script>

  </head>
  <body>
    <p><br/><br/></p>
    <div class = "container">
            <table id="example" class = "table table-bordered table-striped table-hover">
                <thead> 
                    <tr>
                  <th>Video Name</th>
                  <th>File Name</th>
                  <th>Copy</th>

                    </tr>

                </thead>

            </table>
    </div>



  </body>
</html>

And this is my address.js

$.getJSON("http://mlearningessentials.com/vid.php", function(data){

  var items = [];

  $.each(data, function(key, val){
    items.push("<tr>");
    items.push("<td  id=''"+key+"''>"+val.video_name+"</td>");
        items.push("<td id=''"+key+"''>"+val.file_name+"</td>");
          items.push("<td>"+'<button type="button" class="btn btn-primary" id="copy">Copy</button>'+"</td>");



        items.push("</tr>");
 });

  $("<tbody/>", {html: items.join("")}).appendTo("table");

});


 $(document).ready(function(){
    $("#copy").click(function(){
      alert('copied');


    });
  })
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
VLR
  • 312
  • 1
  • 4
  • 18
  • 1
    Learn [Event Delegation](http://learn.jquery.com/events/event-delegation/) use code `$(document).on("click","#copy",function(){` – Satpal Jan 05 '17 at 09:59

3 Answers3

2

You need to trigger event dynamically

$(document).on("click","#copy",function(){
  alert('copied');
});

Read more about event delegation to understand how it works.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
1

For dynamically added elements you have bind the click a bit differently(Event delegation). Try this:

$(document).on("click", "#copy", function() {
  alert('copied');
});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
1

By dynamic DOM try this

$(document).on("click", "#copy", function() {
  alert('copy');

});
Blue
  • 22,608
  • 7
  • 62
  • 92
ricky
  • 1,644
  • 1
  • 13
  • 25