How to replace the cell text of a table with currently selected cell text in jquery

Viewed 38

I have a table with some values. I am getting the current selected value from a jQuery click event as shown below.

When I click 1 I get 1 in console. When I click 2 I get 1 and 2 both.

When I write $(selectedValue).remove() it doesn't work. Also it doesn't work if I write $(selectedValue).text()

I just want the value 2 in console i.e. I want to replace the old value with a newly clicked (or selected) value.

$('td').click(function() {
  var selectedValue = $(this).text(); // get the current cell text
  $(selectedValue).remove(); //this doesn't reset the value
  var row = $(this).parent().text();
  console.log(selectedValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th>First</th>
    <th>Second</th>
    <th>Third</th>
  </tr>
  <tr>
    <td>0</td>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
    <td>5</td>
  </tr>
</table>

1 Answers

nothing wrong with your code, and the values are printed correctly in console, what you are trying to achieve is clear the console before printing the newly selected value, one way to get the result you want is :

  • the best solution is to creat a label inside your html and print the value of the selected cell inside the label instead of the consol

  • manually clear the console after each value selection

  • programmatacclly print new empty lines to simulate the clearing befor every selection like this :

    $('td').click(function() {
      var selectedValue = $(this).text(); // get the current cell text
      var row = $(this).parent().text();
      console.log('\n'.repeat('25'));
      console.log(selectedValue);
    });
    
  • another way is to use a console.clear() function but that's a bit tricky since it changes from a browser to another :

     $('td').click(function() {
        var selectedValue = $(this).text();
        var row = $(this).parent().text();
        // For Chrome
        if (typeof console._commandLineAPI !== 'undefined') {
        console.API = console._commandLineAPI;
        } 
       // for Safari
       else if (typeof console._inspectorCommandLineAPI !== 'undefined') {
       console.API = console._inspectorCommandLineAPI;
       } 
      else if (typeof console.clear !== 'undefined') {
       console.API = console;
       }
       console.API.clear();
       console.log(selectedValue);
     });
    
Related