0

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.

Community
  • 1
  • 1
Henry
  • 1,042
  • 2
  • 17
  • 47

5 Answers5

1

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

jmcgriz
  • 2,819
  • 1
  • 9
  • 11
  • Having done this, is it possible to change the text of the cell clicked from table 1, to the text of cell clicked on table 2? – Henry Jan 28 '16 at 15:36
  • ideally, you'd create a variable `var storecell;` outside of your functions. Then, instead of alerting the cell id, you could save the cell that was clicked to that variable `function doSomethingWithTableCell(cell){ storecell = cell }`. After that, in the click function of your second table, you should be able to get the text of the cell and pass it to your stored cell `storecell.textContent = event.target.textContent` – jmcgriz Jan 28 '16 at 15:54
  • https://jsfiddle.net/lexicalnoscope/rt43xqzu/ showing that functionality with `var storecell;` – jmcgriz Jan 28 '16 at 15:59
  • Great, thanks. Say for example, if I was repersenting each of the menulist items by colour e.g. orange = orange background colour for the cell, apple = green background colour for that cell and so on and if i I wanted to instead of changing the text of table 1 cell change the colour, would that be possible? – Henry Jan 28 '16 at 17:27
  • sure, you can target all element properties in the same way. instead of setting `event.target.textContent`, you'd set `event.target.style.backgroundColor`. Better yet, put your styling in a class (`.apple { background-color: green }`) and add that class to the table cell `event.target.classList.add('apple')` – jmcgriz Jan 28 '16 at 22:06
1

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

brk
  • 48,835
  • 10
  • 56
  • 78
  • This works just like I want, however, I will be adding div tags inside my td tags to control the positioning of text, so do I need to do something like this 'click','td','div' instead of 'click','td',. for example, I will have this ' 
    On-Menu
    '
    – Henry Jan 28 '16 at 15:56
  • to position text inside td you can simply apply css on td. Or at worst put div inside td which is not a good idea.Check this http://stackoverflow.com/questions/1110915/is-a-div-inside-a-td-a-bad-idea Also 'click','td' will be enough you dont need to further delegate it – brk Jan 28 '16 at 16:03
  • Thanks, I have upvoted and I will accept it when I get a chance to implement it in my code. Thanks again :) – Henry Jan 28 '16 at 17:23
  • Hi, this works fine in the fiddle but when I implement in my code it won't work – Henry Jan 29 '16 at 08:30
  • Please have a look at these two links: https://dl.dropboxusercontent.com/u/53441658/menu.html and https://dl.dropboxusercontent.com/u/53441658/menu.html – Henry Jan 29 '16 at 08:32
  • Also, I have updated your fiddle https://jsfiddle.net/jtrrtzy6/15/ and given each menulist item a colour, is it possible to change the colour of of table 1 cells instead of text please – Henry Jan 29 '16 at 08:45
  • @Henry Changing any aspect of the original cell is simple, but of course, you need to know and understand html and css to do it. In my answer (above), the original cell was getting it's text changed with this code: actionCell.innerHTML = this.innerHTML. To change the cell color would simply be: actionCell.style.backgroundColor = (some color value here). Please consider marking my post as the answer. – Scott Marcus Jan 29 '16 at 16:51
  • @Henry If you add: actionCell.style.background = window.getComputedStyle(this, null).backgroundColor; into my code, you get the desired result. Have a look at: https://jsfiddle.net/pz6tc3ae/30/ – Scott Marcus Jan 29 '16 at 17:35
  • it toggles the menulist but it won;t change colour – Henry Jan 29 '16 at 18:02
  • @Henry Did you look at the JSFiddle? It works perfectly. – Scott Marcus Jan 29 '16 at 20:41
  • Yep, I am trying it on the link you sent: https://jsfiddle.net/pz6tc3ae/30/ it toggles the menulist but won't change colour – Henry Jan 29 '16 at 21:00
  • I am trying it in firefox, give me 2 secs I will try it in another browser – Henry Jan 29 '16 at 21:01
  • Strange, works fine in chrome but not in firefox :) also, you see currently it changes text and colour, is it possible to only change colour and keep text as it is already on the cell – Henry Jan 29 '16 at 21:23
  • If you try it in any standards compliant browser, it works. To keep the text simply remove the line about .innerHTML – Scott Marcus Jan 30 '16 at 14:23
  • Hi, user2181397 Nope no luck so far. Hi @scott Marcus, the example you provided works fine in fiddle but when I implement it in my code it does not work. Please have a look here: https://dl.dropboxusercontent.com/u/53441658/test.html and here https://dl.dropboxusercontent.com/u/53441658/code.txt – Henry Feb 01 '16 at 08:37
1

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/

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

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";
}
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
  • Thanks, how can I change the text of the clicked cell to the text of the cell that user clicks from the section table that is triggered please – Henry Jan 28 '16 at 15:21
0

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>
Vicky Gonsalves
  • 11,593
  • 2
  • 37
  • 58
  • Hi, thanks. When user clicks any cell from table 1, it should trigger table 2 (toggle table 2) and when user clicks 1 of the 3 options from table 2, it should change the text of table 1 cell that triggered table 2, is it possible to do is that javascript please? – Henry Jan 28 '16 at 15:23
  • Yes you can do your stuff in `elem.addEventListener('click', function() { //here})` – Vicky Gonsalves Jan 28 '16 at 15:27
  • `elem.addEventListener('click', function() { document.getElementById('someid').innerHTML='sometext'})` – Vicky Gonsalves Jan 28 '16 at 15:38
  • if I am not mistaken, someid is taken from the cell clicked in table 1 and sometext would be replaced text in cell clicked in table 2? – Henry Jan 28 '16 at 15:41
  • `someid` is the id of td which you want to replace text and `sometext` is text you want to replace – Vicky Gonsalves Jan 28 '16 at 15:43