Home > other >  Select only one table cell per row and column
Select only one table cell per row and column

Time:11-06

I have the following table:

<table border="1" cellpadding="5" class="test">
  <tr>
    <td id="1">aaa</td>
    <td id="2">bbb</td>
    <td id="3">ccc</td>
  </tr>
  <tr>
    <td id="4">ddd</td>
    <td id="5">eee</td>
    <td id="6">fff</td>
  </tr>
  <tr>
    <td id="7">ggg</td>
    <td id="8">hhh</td>
    <td id="9">iii</td>
  </tr>
</table>

The condition should be that you can only select one table cell per row and column.

At the moment my script is managing that only one selection per table column is possible, but how can I add additionally that only one cell per table row is selectable, too.

This is my 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();
});

CodePudding user response:

remove all the active class in the clicked row. Insert the following row to your code

 $(this).closest('tr').find('td').removeClass('selected');

So,

$(document).on("click", ".test td", function() {
    let index = $(this).index() 1;
    $(this)
        .closest('table')
        .find('tr>td:nth-child(' index ')')
        .removeClass('selected');
    $(this).closest('tr').find('td').removeClass('selected'); // remove 'active' class of the row
    var col1 = $(this).addClass('selected').text();
});

CodePudding user response:

A solution for select "one cell per table row"

$(document).on("click", ".test td", function() {
    let index = $(this).index() 1;
  console.log(index)
    $(this)
    .closest('tr').children('td')
    .removeClass('selected');
  
    $(this).addClass('selected')

});
  • Related