Onclick hide div element - javascript

I have a link that shows/hides a content within a div upon click, what I'm trying to do is have a button that will hide a specific div(the content in sectiontohide1) within the div(sectiontohide)upon click. I've got the Javascript working for the first link(sectiontohide) and it works but I can't figure out how to get the second link to hide the div
<a id="trackAttendance1" onclick="loadtable('sectiontohide');" class="trackAttendance" href="#">Track Absences</a>
<div id="sectiontohide" style="display:none;">
<table>
<div id="sectiontohide1">
<tr>
<td>Web Programming Seminar</td>
<th id="absent" rowspan="2">Absent</th>
</tr>
<tr>
<td>TUESDAY 2:00-3:00 - 21/02/2017</td>
</tr>
</div>
<td>Management in IT</td>
<th id="absent" rowspan="2">Absent</th>
<tr>
<td>FRIDAY 9:00-11:00 - 24/02/2017</td>
</tr>
<tr>
<td>Web Programming Lecture</td>
<th id="absent" rowspan="2">Absent</th>
</tr>
<tr>
<td>FRIDAY 12:00-1:00 - 24/02/2017</td>
</tr>
</table>
<a id="trackAttendance1" onclick="hidediv('sectiontohide1');" class="close" href="#">Hide Element</a>
My Javascript for showing/hiding the table
function loadtable(id){
var divelement = document.getElementById(id);
if(divelement.style.display =='none')
divelement.style.display = 'block';
else
divelement.style.display = 'none';
}

Your loadtable function actually toggles the visibility of the element by the given id.
So you can run it for showing / hiding for the other parts too. For this it should be sufficient to change the click handler of the close button to loadtable('sectiontohide1');
But there are some other issues too, for example :
A div can be placed in a table only if it is surrounded by a <td></td> or <th></th>
<th> tag is for header so use it only on top of the table, you can use css for styling the cells
<td> and <th> tags should always be surrounded by a <tr></tr>

Looks like you were on the right track. To just hide the div, try something like:
function hidediv(id) {
var divelement = document.getElementById(id);
divelement.style.display = 'none';
}

Related

Change button text of a cloned element

Making an food ordering app. There is a first table with all items you can choose. Each item have a button. On this button click it clones the line and put it in a second table containing your chosen items. I would like to change the text content of the button when the element go to the second table. Like "+" in the first table become "-" in the second table (to next delete the item of the second table on "-" click)
HTML
<h1>CHOOSE</h1>
<table id="starters">
<tr>
<th>PRODUCT</th>
<th>PRICE</th>
<th>ADD TO CART</th>
</tr>
<tr>
<td>Cherry</td>
<td>6</td>
<td><button class="item_button">+</button></td>
</tr>
<tr>
<td>Peach</td>
<td>8</td>
<td><button class="item_button">+</button></td>
</tr>
<tr>
<td>Strawberry</td>
<td>12</td>
<td><button class="item_button">+</button></td>
</tr>
</table>
<h1>YOUR CHOICE</h1>
<table id="products_cart">
</table>
JS
let basket = document.getElementById("products_cart")
let buttons = document.querySelectorAll('.item_button');
for (button of buttons) {
button.addEventListener('click', cloneLine);
}
function cloneLine(e) {
let td = e.target.parentNode;
let tr = td.parentNode;
let clone = tr.cloneNode(true);
basket.appendChild(clone);
}
I tried different things like to get (querySelectorAll) the buttons and change their innerHTML (or textContent or innerText) with no success. I also tried to create another button and to replace the former by the newer.

Element in div gets removed as a child but can't be used again

I am trying to display a hidden table in a div then hide it again with display: none/block toggle. It works. But, I can't get it to appear again once I toggle to display: none to hide it.
HTML:
The HTML has an empty div with id = tableContainer.
Next to it, I have a table with the names of animal families in each cell, along with a button. When the button is clicked, it takes the name of the animal family from that particular cell, finds the table of animal species with that name and switches from display: none to display:block and display it /inside the div. Then, if I click the button again, it toggles the display back to display: none.
When I click a button in another cell, it clears the div and displays the new table.
All good.
But, if I click a button that was previously used, the table that has now gone is no longer available.
I have gone through all sorts of hoops playing with removeChild and all that but no luck. I am currently using innerHTML to clear the div, but I'm missing something with the class name.
Console error says: tabletest2.html:523 Uncaught TypeError: Cannot read property 'classList' of null
at toggle (tabletest2.html:523)
at HTMLButtonElement.onclick (tabletest2.html:72)
So, it seems to me that it can't toggle any more because the table now no longer exists, or I may be wrong with that as I didn't delete the child element (I think).
<body>
<table>
<tbody>
<tr>
<td>Genus</td>
<td>Benthobatis
<button onclick="toggle(this, parentNode.firstChild)">Click me</button></td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis
<button onclick="toggle(this, parentNode.firstChild)">Click me</button></td>
</tr>
</tbody>
</table>
<!-- <======== div display container here ================>-->
<div id="tableContainer"></div>
<table id="Benthobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th>Benthobatis</th>
</tr>
<tr>
<td>Benthobatis kreffti</td>
<td>Brazilian Blind Electric Ray</td>
</tr>
</tbody>
</table>
<!-- <==================================-->
<table id="Diplobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th> Diplobatis </th>
</tr>
<tr>
<td>Diplobatis colombiensis</td>
<td>Colombian electric ray</td>
</tr>
</tbody>
</table>
</body>
<script>
function toggle(ele, tableName) {
var myTableDisplayDiv = document.getElementById("tableContainer").childNodes;
if (myTableDisplayDiv.length != 0) {
document.getElementById("tableContainer").innerHTML = "";
}
var myTableName = tableName.textContent;
var myTable = document.getElementById(myTableName);
myTable.classList.toggle("hide");
document.getElementById("tableContainer").appendChild(
document.getElementById(myTableName)
);
}
</script>
<style>
.hide {
display: none;
}
Explanations
"Why are my tables deleted if I'm only changing display option, not removing the child node?".
This destroys everything within:
document.getElementById("tableContainer").innerHTML = "";
This moves the chosen table to #tableContainer:
document.getElementById("tableContainer").appendChild(
document.getElementById(myTableName)
So in three clicks there's nothing left. Of course this is if the table can be identified correctly which it wasn't. The .textContent of .parentNode.firstChild reference was lost because this refers to a global context not the button. This is why on-event attributes (among other various reasons) are discouraged. Although not a critical issue as the ones previously mentioned, you should seriously have some variations to the names:
tableName
myTableName
myTable
myTableDisplayDiv
tableContainer
I'm pretty sure this naming scheme did not facilitate debugging.
Solutions
Before you place a table into #tableContainer where it gets destroyed, make a copy with .cloneNode().
Remove the onclick attributes and either use onclick property (like in the demo) or .addEventListener().
Register an ancestor element of both buttons (i.e. tbody), from there both buttons can be clicked and easily isolated and referenced by using event.target.
Now the reference to the clicked button (event.target) can now be referenced:
var tableName = event.target.parentNode.firstChild.textContent
And then the table can finally be referenced:
var table = document.getElementById(tableName)
Demo
document.querySelector('tbody').onclick = toggle;
function toggle(event) {
var clicked = event.target;
if (clicked.tagName === 'BUTTON') {
var genus = clicked.parentNode.firstChild.textContent;
var table = document.querySelector('#' + genus);
var display = document.getElementById("display");
display.innerHTML = "";
var clone = table.cloneNode(true);
display.appendChild(clone);
clone.classList.toggle('hide');
}
}
.hide {
display: none;
}
<table>
<tbody>
<tr>
<td>Genus</td>
<td>Benthobatis
<button>Click me</button></td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis
<button>Click me</button></td>
</tr>
</tbody>
</table>
<!-- <======== div display container here ================>-->
<div id="display"></div>
<table id="Benthobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th>Benthobatis</th>
</tr>
<tr>
<td>Benthobatis kreffti</td>
<td>Brazilian Blind Electric Ray</td>
</tr>
</tbody>
</table>
<!-- <==================================-->
<table id="Diplobatis" class="hide">
<tbody>
<tr>
<th>Genus</th>
<th> Diplobatis </th>
</tr>
<tr>
<td>Diplobatis colombiensis</td>
<td>Colombian electric ray</td>
</tr>
</tbody>
</table>
Your code is kind of complex to understand but if you just want to toggle the table, I think this is the best way.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.hide {
display: none;
}
</style>
</head>
<body>
<div class="table-container">
<button class="toggle-btn">Click me</button>
<table>
<tr>
<td>Genus</td>
<td>Benthobatis</td>
</tr>
<tr>
<td>Genus</td>
<td>Diplobatis</td>
</tr>
</table>
</div>
<script>
const table = document.querySelector('table'),
btn = document.querySelector('.toggle-btn');
btn.addEventListener("click", () => {
table.classList.toggle("hide")
})
</script>
</body>
</html>

I have around 17 tables in my HTML document and want them to appear separately when I click on them through a separate button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have 17 tables in my HTML document. I want them all under a separate button. So the table for the year 2000 under a button that says: Table for year 2000 below! I can do the first one. But when I try to apply the JavaScript code for the button on other tables I keep getting the first table.
This is my JavaScript code:
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
This is my HTML code for the tables, I'm just showing the first 2 tables because it's 17 times copy paste:
<!--Table for the year 2000 below-->
<button onclick="myFunction()">Table for the year 2000 below!</button>
<div id="myDIV" style="display:none;">
+<table>...
</table>
<br><br><br>
</div>
<!--Table for the year 2001 below-->
<button onclick="myFunction()">Table for the year 2001 below!</button>
<div id="myDIV" style="display:none;">
+<table>...
</table>
<br><br><br>
</div>
Alright so hear me out, I now with a quick Google search that getElementById can only hold one parameter. I got that. I tried to copy my JS code and change the ID in the function and the HTML code, but everytime I try that I can only show the latest table I applied that method to, doesn't matter which button I press.
I have also seen people on this forum use querySelectorAll but that didn't work out for me.
Could someone help me out with this? I expect my method to work, use the same function that works on the first table but keep changing the ID. But clearly it didn't.
Few inputs:
Id should be unique to an element
The event handler should be given some inputs to identity which element (table in this case) it has to work with.
To cover all these, a sample snippet is included to help you further.
Detailed breakdown:
We are attaching a click event handler to all the button elements
We try to identify all button elements using document.querySelectorAll
How do we identity which table to show on a click event? We can put that additional details in data-* attributes. Based on that we are selecting that specific table using document.getElementById
Detailed comments included in the code-base.
window.onload = function() {
// Get all the `button` elements
var buttons = document.querySelectorAll("button");
// To store the current `table`
var currentTable = null;
// Loop over each button element and attach an handler to `click` event
buttons.forEach((element, index, array) => {
element.addEventListener("click", function() {
// Get the associated table using the `data-table` attribute of this button
var tableId = element.getAttribute("data-table");
// Good to go?
if (tableId) {
// Hide the current `table` if we have any displayed
if (currentTable !== null) {
currentTable.style.display = "none";
}
// Store the current table and `display` it
currentTable = document.getElementById(tableId);
currentTable.style.display = "table";
}
});
});
}
table {
display: none;
}
#table1 {
border: 1px solid red;
}
#table2 {
border: 1px solid blue;
}
<button id="btnForTable1" data-table="table1">Show Table 1</button>
<button id="btnForTable2" data-table="table2">Show Table 2</button>
<!-- Table 1 -->
<table id="table1">
<tr>
<th>First name</th>
<th>Last name</th>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
</tr>
<tr>
<td>Jane</td>
<td>Doe</td>
</tr>
</table>
<!-- Table 2 -->
<table id="table2">
<thead>
<tr>
<th>Header content 1</th>
<th>Header content 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Body content 1</td>
<td>Body content 2</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Footer content 1</td>
<td>Footer content 2</td>
</tr>
</tfoot>
</table>

How to enable anchor tag on a table row?

<div class="table-responsive">
<table class="table table-bordered">
<tbody>
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
<th>head5</th>
<th>head6</th>
<th>head7</th>
</tr>
<a href="#">
<tr>
<td>col1</td>
<td>col2</td>
<td>col3</td>
<td>col4</td>
<td>col5</td>
<td>col6</td>
<td>col7</td>
</tr>
</a>
</tbody>
</table>
</div>
I have got this html page and i need to make the entire row as an anchor tag so when i hover over the row and click it I can goto another page. But When i try to execute it, the DOM throws the anchor tag outside table tags and it does not work. How can i implement this ?
You can't add <a> tag in a <table>.
You can only add content in <td> tag.
Try to add a onclick attribute with document.location.href+='#anchor'; return false;
Example
table {
height:200px;
}
#test{
height:400px;
background-color:grey;
}
<table>
<tr onclick="document.location+='#test';return false;">
<td>
click
</td>
<td>
click
</td>
</tr>
</table>
<div class="test" id="test"></div>
Update
For go to another page use
window.location.href="url";
instead of
document.location
You can't.
A link can exist inside a table cell or completely contain a table. There are no options in between.
You could put a link in the first cell and then apply some JavaScript:
jQuery("tr").on("click", function (e) {
location = jQuery(this).find("a").attr("href");
});
It is not a valid standard. You can use JS for acnchor. For example:
$('.table-bordered tr td').on("click", function(){
window.location.href= $(this).parent().attr('href');
});
TR defination can be:
<tr href="http:/www.yahoo.com">.....</tr>

Javascript hide/show tabs using JQuery

I have a quick question of how I can use jQuery tabs (you click on link button to display/hide certain divs). The div id matches the href of the link:
HTML links:
<table class='layout tabs'>
<tr>
<td>Site</td>
<td>Number</td>
</tr>
<tr>
<td>Student</td>
<td>School</td>
</tr>
</table>
</div>
div that needs to display/hide:
<div id="site">
<table class='explore'>
<thead class='ui-widget-header'>
<tr>
<th class=' sortable'>
Site
</th>
<th class=' sortable'>
Number
</th>
</tr>
</thead>
</table>
</div>
$("table.tabs a").click( function() {
var id = $(this).attr( "href" );
var div = $(id);
div.toggle();
} );
This will get you exactly what you're asking. However, I suspect that you also want to hide all other divs when one div is shown. True?
Ok, now that you've responded that it's true, here's your new code.
You also should add a class (in my code - "tab-div") to all your DIVs, in order to have them easily selectable all together.
$("table.tabs a").click( function() {
var id = $(this).attr( "href" );
// Hide all the tab divs
$(".tab-div").hide();
// Then show the one that's been clicked
$(id).show();
} );

Categories