Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript onClick event in all cells

I'm learning JavaScript and I've not that much experience. But I'm making a HTML table and I want to add in every table cell (<td>) a onClick event.

<table id="1">
    <tr>
        <td onClick="tes()">1</td><td onClick="tes()">2</td>
    </tr>
    <tr>
        <td onClick="tes()">3</td><td onClick="tes()">4</td>
    </tr>
</table>

Is there another way to do this event in every cell?

like image 792
Sanderr Avatar asked Oct 03 '13 09:10

Sanderr


1 Answers

I know this is a bit old, but you should use a click envent on the table and use the target value to get the cell. Instead of having a 10 x 10 table = 100 event you will have only 1.

The best thing with that method is when you add new cells you don't need to bind an event again.

$(document).ready( function() {
    $('#myTable').click( function(event) {
      var target = $(event.target);
      $td = target.closest('td');
      
      $td.html(parseInt($td.html())+1);
      var col   = $td.index();
      var row   = $td.closest('tr').index();

      $('#debug').prepend('<div class="debugLine">Cell at position (' + [col,row].join(',') + ') clicked!</div>' );
      
    });
  });
td {
  background-color: #555555;
  color: #FFF;
  font-weight: bold;
  padding: 10px;
  cursor: pointer;
  }

#debug {
    background-color: #CCC;
    margin-top: 10px;
    padding: 10px;
  }

#debug .debugLine {
    margin: 2px 0;
    padding: 1px 5px;
    background-color: #EEE;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
  <tr>
    <td>0</td>    
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
  <tr>
    <td>0</td>    
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
  <tr>
    <td>0</td>    
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
    <td>0</td>
  </tr>
</table>

<div id="debug"></div>
like image 155
Zack Niwa Avatar answered Sep 30 '22 22:09

Zack Niwa