0

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);

});
Andy
  • 61,948
  • 13
  • 68
  • 95
Berstos
  • 179
  • 10
  • 3
    To get the data attribute just do this of the selected `tr` -> Change your return to this in your map function -> `return $(this).data('value')` - should work fine. Your code looks fine. Here is working fiddle: https://jsfiddle.net/6mw97vxL/ – Always Helping Nov 08 '21 at 01:40
  • Does this answer your question? [How can I get the data-id attribute?](https://stackoverflow.com/questions/5309926/how-can-i-get-the-data-id-attribute) – Always Helping Nov 08 '21 at 01:55

1 Answers1

3

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>
Spectric
  • 30,714
  • 6
  • 20
  • 43