Henry
Henry

Reputation: 1042

How to check which table cell triggered an action JavaScript

I am fairly new to web development and to get hang of doing simple tasks I am working on a project and it turns out for a task I want to carry out I have to use Javascript but having only little knowledge of Javascript I can't figure out how to do what I want and I have searched online but haven't been able to finding anything of use:

How to know element clicked within a table?

How to access specific cell of clicked table row in javascript

...

Here is the project code I have written so far:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Menu</title>
<script>
    function toggleTable() {
    var lTable = document.getElementById("menulist");
    lTable.style.display = (lTable.style.display == "table") ? "none" : "table";
}
</script>
</head>

<body>
<table width="300" border="1" id="menuitems">
  <tbody>
    <tr>
      <td onclick="toggleTable()" id="cell1">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell2">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell3">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell4">&nbsp;On-Menu</td>
    </tr>
    <tr>
      <td onclick="toggleTable()" id="cell5">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell6">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell7">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell8">&nbsp;On-Menu</td>
    </tr>
    <tr>
      <td onclick="toggleTable()" id="cell9">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell10">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell11">&nbsp;On-Menu</td>
      <td onclick="toggleTable()" id="cell12">&nbsp;On-Menu</td>
    </tr>
  </tbody>
</table>
<table width="300" border="1" id="menulist">
  <tbody>
    <tr>
      <td id="cellorange">&nbsp;Orange</td>
    </tr>
    <tr>
      <td id="cellapple">&nbsp;Apple</td>
    </tr>
    <tr>
      <td id="cellbanana">&nbsp;Banana</td>
    </tr>
  </tbody>
</table>
</body>
</html>

here I have 2 sets of table, 1 containing empty cells respresented by 'On-Menu' and another containing list of options. Please have a look here: https://jsfiddle.net/pz6tc3ae/

The project so far, when clicked on each table cell triggers a javascript function toggleTable(), which toggles the section table called menulist containing, Orange, Apple and Banana.

Table 1 = menuitems Table 2 = menulist

What I want to know is:

The user can click on any cell within Table 1, which will trigger the toggleTable function and toggle (show/hide) table 2. What I want to know is which table cell triggered table 2.

Having the first task done, within table 2, I have given ids to each of the three options orange, apple and banana, when user clicks on any of these options I want the text of this cell to be written on the cell from table 1 that triggered table 2 in first place.

I have no clue on how I can go about doining this and having little knowledge of Javascript, my research haven't proved to as effective as I wanted it to be, therefore I would really appreciate if someone can help me out.

Thanks in advance and if my question was not clear enough please let me know.

Upvotes: 0

Views: 873

Answers (5)

Scott Marcus
Scott Marcus

Reputation: 65835

You don't need to assign the event handler to each cell of the first table and frankly, that uses a very old technique to do it that is not favored any longer. Additionally, you don't need to add &nbsp; before each piece of text in the cells, you can just use a regular space since clients only strip out spaces when there is more than one of them.

Here is a non-JQquery (straight JavaScript) way to solve your problem:

    var firstTable = document.getElementById("table1")
    var firstTableCells = firstTable.getElementsByTagName("td");
    var lTable = document.getElementById("menulist");
    var lTableCells = null;
    var actionCell = null;
    for(var i = 0; i < firstTableCells.length; ++i){
        firstTableCells[i].addEventListener("click", function(evt){
             actionCell = evt.srcElement;
             lTable.style.display = (lTable.style.display === "table") ? "none" : "table";
             if(lTable.style.display === "table"){
                  lTableCells = lTable.getElementsByTagName("td");
                  for(var x = 0; x < lTableCells.length; ++x){
                       lTableCells[x].addEventListener("click", function(){
                            actionCell.innerHTML = this.innerHTML;
                       });
                  }
             }
         });
    }

JSFiddle: https://jsfiddle.net/pz6tc3ae/17/

Upvotes: 1

brk
brk

Reputation: 50326

You dont need to attach onclick handler with every td. This is tedious task. Instead just delegate the event. Here is modified snippet

HTML

<table width="300" border="1" id="menuitems">
  <tbody>
    <tr>
      <td id="cell1">&nbsp;On-Menu</td>
      <td id="cell2">&nbsp;On-Menu</td>
      <td  id="cell3">&nbsp;On-Menu</td>
      <td id="cell4">&nbsp;On-Menu</td>
    </tr>
    <tr>
      <td id="cell5">&nbsp;On-Menu</td>
      <td  id="cell6">&nbsp;On-Menu</td>
      <td  id="cell7">&nbsp;On-Menu</td>
      <td  id="cell8">&nbsp;On-Menu</td>
    </tr>
    <tr>
      <td id="cell9">&nbsp;On-Menu</td>
      <td  id="cell10">&nbsp;On-Menu</td>
      <td  id="cell11">&nbsp;On-Menu</td>
      <td id="cell12">&nbsp;On-Menu</td>
    </tr>
  </tbody>
</table>
<table width="300" border="1" id="menulist">
  <tbody>
    <tr>
      <td id="cellorange">&nbsp;Orange</td>
    </tr>
    <tr>
      <td id="cellapple">&nbsp;Apple</td>
    </tr>
    <tr>
      <td id="cellbanana">&nbsp;Banana</td>
    </tr>
  </tbody>
</table>

The user can click on any cell within Table 1, which will trigger the toggleTable function and toggle (show/hide) table 2. What I want to know is which table cell triggered table 2.

This js does rest of the work

var cachClickElem =0;   // a variable to track the clicked td of 1st table
$("#menuitems").on('click','td',function(event){
cachClickElem = this.id   // update variable with the id of clicked td
var lTable = document.getElementById("menulist");
 // toggle display of second table
    lTable.style.display = (lTable.style.display == "table") ? "none" : "table";

})
$("#menulist").on('click','td',function(event){
// get text content of td from second table  which is clicked    
 var getContent =$(this).text(); 
if(cachClickElem != 0){
 // Change text of last clicked td of 1st table
  $("#"+cachClickElem).text(getContent); 
 }
})

JSFIDDLE

Upvotes: 1

jmcgriz
jmcgriz

Reputation: 3368

Here's an updated fiddle -> https://jsfiddle.net/lexicalnoscope/o8dn70h7/1/

In this case, rather than binding the click event to each cell individually, it's cleaner to bind to the parent table instead:

<table width="300" border="1" onclick="toggleTable(event)">

Once inside the toggleTable function, event.target identifies the element that generated the click event. You can ensure that it's a table cell by checking that the tagname is equal to "TD"

if(event.target.tagName == "TD")

Once you've executed your menu toggle, then the table cell gets passed to a handler function to do whatever you need to do with it: doSomethingWithTableCell(event.target) In this case, I have it alerting the id for starters:

function doSomethingWithTableCell(cell){
  alert(cell.id)
}

Working from there, you should be able to use a similar pattern to handle the click events on the second table

Upvotes: 1

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11717

Simple javascript solution:
Remove all onclick attributes from your HTML and attach EventListener

 document.addEventListener('DOMContentLoaded', function() {
   [].map.call(document.querySelectorAll('#menuitems td'), function(elem) {
     elem.addEventListener('click', function() {
       alert(this.id)
     })
   })
 }, false)
<table width="300" border="1" id="menuitems">
  <tbody>
    <tr>
      <td id="cell1">&nbsp;On-Menu</td>
      <td id="cell2">&nbsp;On-Menu</td>
      <td id="cell3">&nbsp;On-Menu</td>
      <td id="cell4">&nbsp;On-Menu</td>
    </tr>
    <tr>
      <td id="cell5">&nbsp;On-Menu</td>
      <td id="cell6">&nbsp;On-Menu</td>
      <td id="cell7">&nbsp;On-Menu</td>
      <td id="cell8">&nbsp;On-Menu</td>
    </tr>
    <tr>
      <td id="cell9">&nbsp;On-Menu</td>
      <td id="cell10">&nbsp;On-Menu</td>
      <td id="cell11">&nbsp;On-Menu</td>
      <td id="cell12">&nbsp;On-Menu</td>
    </tr>
  </tbody>
</table>
<table width="300" border="1" id="menulist">
  <tbody>
    <tr>
      <td id="cellorange">&nbsp;Orange</td>
    </tr>
    <tr>
      <td id="cellapple">&nbsp;Apple</td>
    </tr>
    <tr>
      <td id="cellbanana">&nbsp;Banana</td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Venkata Krishna
Venkata Krishna

Reputation: 15112

DEMO -> https://jsfiddle.net/pz6tc3ae/1/

pass the html element by onclick="toggleTable(this)"

and in your function, you can read back as function toggleTable(element) {

function toggleTable(element) {
    alert(element.id); // alerts the id
    var lTable = document.getElementById("menulist");
    lTable.style.display = (lTable.style.display == "table") ? "none" : "table";
}

Upvotes: 0

Related Questions