0

I am looking to be able to pass a javascript variable as data in an html table row element and have the data logged when that row element is click. The code that is appending/creating the table rows is inside an ajax call. Outside of the call in a click function I want to click on a table row that was created/appened and get the data variable. Here is the current code

$.ajax({ 
...
  var name = 'superman'
  $('#myTable tbody').append('<tr class = 'table_class' id = 'table_id' data-person = name></tr>');
  });
...
$('#myTable tbody').on('click','table_class', function(){
    console.log($(this).dataset.name);
}

The expected result of the console log is to be: superman.

1
  • 1
    Your JS snippet is invalid... Commented Feb 4, 2021 at 16:29

2 Answers 2

1

If you are adding the class to the <tr>, make sure you include at least one <td> child so that you can actually click on the row.

var table_id = 'table_id';
var table_class = 'table_class';

// AJAX logic start...
var name = 'superman';
$('#myTable tbody').append(
  $('<tr>')
  .attr('id', table_id)
  .addClass(table_class)
  .data('person', name)
  .append(
    $('<td>').text(name)
  )
);
// AJAX logic end...

$('#myTable tbody').on('click', `.${table_class}`, function() {
  console.log($(this).data('person'));
});
#myTable { border-collapse: collapse; }

#myTable, #myTable th, #myTable td { border: thin solid grey; }

#myTable th, #myTable td { padding: 0.5em; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
  <thead>
    <tr>
      <th>Name</th>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>

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

Comments

1

You have more errors:

  1. data-person= must be data-name
  2. $('#myTable tbody').on('click','table_class', function(){ should be: $('#myTable tbody').on('click','.table_class', function(){
  3. $(this).dataset. should be this.dataset or $(this).data

The snippet:

var name = 'superman';
$('#myTable tbody').append('<tr class ="table_class" id="table_id" data-name="' + name + '"><td>XXXX</td></tr>');


$('#myTable tbody').on('click', '.table_class', function () {
    console.log(this.dataset.name);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
    <tbody>

    </tbody>
</table>

Comments

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.