user14572493
user14572493

Reputation: 3

How to make dynamic HTML table data (created using jQuery) clickable?

I am new to these and have tried creating an HTML table dynamically using jQuery. The code is as below. It works fine.

How can I make the table data (value.id) clickable so that it redirects to a different page?

$(document).ready(function() {
  var tableData = '';
  $.each(xyz, function(key, value) {
    tableData += '<tr>';
    tableData += '<td>' + value.id + '</td>';
    tableData += '<td>' + value.name + '</td>';
    tableData += '</tr>';
  });
  $('#table').append(tableData);
  //}); 
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead></thead>
  <tbody id="table"></tbody>
</table>

Upvotes: 0

Views: 56

Answers (3)

imvain2
imvain2

Reputation: 15847

I prefer to give the clickable elements a class to reference:

I also have some CSS that sets the cursor to a pointer.

     $(document).ready(function () { 
                
                    var tableData = ''; 

                    $.each(xyz, function (key, value) { 

                        tableData += '<tr>'; 
                            tableData += '<td class="link">' +  
                            value.id + '</td>'; 

                            tableData += '<td>' +  
                            value.name + '</td>';

                            tableData += '</tr>'; 
                    }); 
                      
                    $('#table').append(tableData); 
                //}); 
            }); 

$(document).on("click","#table .link",function(){
     console.log($(this).html());
});

.link{cursor:pointer;}

Upvotes: 0

mplungjan
mplungjan

Reputation: 177689

Like this

const xyz = [{
    id: 1,
    name: "one"
  },
  {
    id: 2,
    name: "two"
  }
]
$(function() {
  const tableData = xyz.map(item => (`<tr><td class="id">${item.id}</td>
  <td>${item.name}</td></tr>`));
  $('#table').append(tableData.join(""));
  $('#table').on("click", ".id", function() {
    const id = this.textContent
    console.log(id);
    // location = "https://google.com/search?q="+id;
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table>
  <thead></thead>
  <tbody id="table"></tbody>
</table>

Upvotes: 1

Esteban MANSART
Esteban MANSART

Reputation: 561

You can enclose your tile content with a "a" tag

                        `tableData += '<tr>'; 
                        tableData += '<td><a href="/you-url/' +value.id+ '">' + 
                        value.id + '<'/a></td>'; 

                        tableData += '<td>' +  
                        value.name + '</td>';

                        tableData += '</tr>';`

Upvotes: 0

Related Questions