Get the specific data cell in the table when you click the button

advertisements

I was wondering how to get the specific data cell if the button is clicked inside my the HTML table. I used jquery on it but only the first row was alert.

This is my Html.

 <!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="table" class = "table table-bordered table-striped table-hover">
                <thead>
                    <tr>
                  <th>State</th>
                  <th>Street Address</th>
                   <th>Street Name</th>
                  <th>Copy</th>

                    </tr>

                </thead>

            </table>
    </div>

  </body>
</html>

This is my .js

$.getJSON("MOCK_DATA.json", function(data){

  var items = [];

  $.each(data, function(key, val){
    items.push("<tr>");
    items.push("<td  id=''"+key+"''>"+val.state+"</td>");
    items.push("<td id=''"+key+"''>"+val.street_add+"</td>");
    items.push("<td id=''"+key+"''>"+val.street_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).on("click", "#copy", function() {
       alert("Copied " + $("td" ).html());
});

The data of the table is on json


One approach to accomplish that:

1) use data-attributes at the button tag with your desired value;

2) remove id from the button and add a semantic class do the button to allow event binding later (you can have only one unique id per document).

3) bind event directly to the button and get value reading the correspondent data-attr.

Something like that:

...
items.push("<td>"+'<button type="button" class="btn btn-primary btn-copy" data-value="' + val.street_name + '">Copy</button>'+"</td>");
...
$(document).on("click", ".btn-copy", function() {
       var value = $(this).attr('data-value');
       alert("Copied " + value);
});