Chogori Posted October 20, 2015 Share Posted October 20, 2015 I am trying to write a script, which: • after the click on any <td> cell makes <div id="pole"> visible • after the click on one of the <li> from <div id="pole> take the content of this li and insert it to <td> cell, which onclick makes <div> visible AND change <div> visibility back to "hidden" Everything works almost fine. Almost... For example: 1) I click on some <td> cell and then choose <li> "strength" - that´s ok, "strength" is written to that cell 2) After that I click on another cell and choose <li> "endurance" - "endurance" is written to that cell, BUT the content of the first cell is changed to "endurance" too Can somebody fix it? And explain me where is the mistake? Whole code is here: https://jsfiddle.net/4odhrgLL/2/ Thanks a lot and sorry for my english... var ParentTable = document.getElementById("mytable");var childTD = ParentTable.getElementsByTagName("td");var pole = document.getElementById("pole");var rest = document.getElementById("rest");var treningType = pole.getElementsByTagName("li");for(i=0;i<childTD.length;i++) { childTD[i].addEventListener("click", clickTD);} function clickTD(e) { var currentTD = e.target; pole.style.visibility = "visible"; for(j=0;j<treningType.length;j++) { treningType[j].addEventListener("click", insertToTD); } function insertToTD(e) { var currentTraining = e.target; currentTD.innerHTML = currentTraining.innerHTML; pole.style.visibility = "hidden"; } } Link to comment Share on other sites More sharing options...
justsomeguy Posted October 20, 2015 Share Posted October 20, 2015 You're assigning the li click handler inside the td click handler. So, every time you click on a td you're assigning another handler for the li click. If you click on 5 tds then it's going to run li click handlers 5 times the next time you click. 1 Link to comment Share on other sites More sharing options...
Chogori Posted October 20, 2015 Author Share Posted October 20, 2015 And what is the best solution? Make currentTD global and then wrap whole script in function? Like this? https://jsfiddle.net/4odhrgLL/3/ Sorry for (maybe) stupid questions, I am JS newbie Link to comment Share on other sites More sharing options...
justsomeguy Posted October 20, 2015 Share Posted October 20, 2015 That's not a bad way to do it. Another way would be to use a data attribute on each LI to store the ID or something for the TD that was clicked on, but that may get a little clunky. Another way would be to give the TD a class, and then inside the LI handler you look up the element with that class, write to it, and then remove the class. 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now