Get "data" values of selected table cells

I have the following table:

<table border="1" cellpadding="5" class="test">
  <tr>
    <td id="1" data-value="50">aaa</td>
    <td id="2" data-value="60">bbb</td>
    <td id="3" data-value="70">cc</td>
  </tr>
  <tr>
    <td id="4" data-value="80">ddd</td>
    <td id="5" data-value="90">eee</td>
    <td id="6" data-value="100">fff</td>
  </tr>
  <tr>
    <td id="7" data-value="110">ggg</td>
    <td id="8" data-value="120">hhh</td>
    <td id="9" data-value="130">iii</td>
  </tr>
</table>

My script allows that you can select only one table cell per row and column.
The selected table cells get a "selected" class on click.

Now I need the "data-value" of the selected table cells which should be stored inside an array. Therefore I tried the map method, but I just get an empty array as the result.

This is the script and the JS Fiddle:

$(document).on("click", ".test td", function() {
    let index = $(this).index()+1;
    $(this)
    .closest('table')
    .find('tr>td:nth-child('+index+')')
    .removeClass('selected');
  
    var col1 = $(this).addClass('selected').text();
    
     var arr = $('.selected').map(function () {
                            return this.value
                        }).get();
        
       console.log(arr);

});

>Solution :

You are retrieving the selected element’s value property instead of its data-value attribute value.

To get its data-value attribute value, you can use jQuery.data.

$(document).on("click", ".test td", function() {
  let index = $(this).index() + 1;
  $(this)
    .closest('table')
    .find('tr>td:nth-child(' + index + ')')
    .removeClass('selected');

  var col1 = $(this).addClass('selected').text();

  var arr = $('.selected').map(function() {
    return $(this).data('value')
  }).get();

  console.log(arr);

});
.selected {
  background: #333;
  color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1" cellpadding="5" class="test">
  <tr>
    <td id="1" data-value="50">aaa</td>
    <td id="2" data-value="60">bbb</td>
    <td id="3" data-value="70">cc</td>
  </tr>
  <tr>
    <td id="4" data-value="80">ddd</td>
    <td id="5" data-value="90">eee</td>
    <td id="6" data-value="100">fff</td>
  </tr>
  <tr>
    <td id="7" data-value="110">ggg</td>
    <td id="8" data-value="120">hhh</td>
    <td id="9" data-value="130">iii</td>
  </tr>
</table>

Leave a Reply