M. Spencer M. Spencer - 4 months ago 13
HTML Question

Click numbered div to show/hide table of same number

I have a series of tabs (divs) that are being automatically numbered on page load and a series of tables also being automatically numbered. What is a short jquery script to show/hide the tables based on the div clicked. Ex. "tab1" shows/hides "table1", "tab2" shows/hides "table2", etc.

I was hoping for a way to have this work for an infinite amount of these pairs, rather than writing

$('.tab1').click(function(){
$('.table1').toggle();
});

$('.tab2').click(function(){
$('.table2').toggle();
});


for each one

EDIT:

Link to example: https://jsfiddle.net/captainmorganms/o1ndn2b2/3/

Answer

Given the markup provided in the example Fiddle, you can achieve this for any number of tables with a single event listener and a few extra attributes, like so:

document.querySelector(".section").addEventListener("click",function(event){
    var target=event.target,table;
    if(table=target.dataset.table)
        if(table=document.getElementById(table))
            table.classList.toggle("hide");
},0);
.section>div{
    display:inline-block;
    cursor:pointer;
    margin:0 5px;
    border:1px solid;
    padding:3px;
}
table{
    border:1px solid;
    border-collapse:collapse;
    margin-top:15px;
}
table.hide{
    display:none;
}
td{
    border:1px solid;
    padding:5px;
    min-width:50px;
    height:30px;
}
<div class="section">
	<div data-table="table1">Tab1</div>
	<div data-table="table2">Tab2</div>
	<div data-table="table3">Tab3</div>
</div>
<table class="hide" id="table1">
	<tr><td>Table 1</td><td></td><td></td><td></td><td></td></tr>
	<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
<table class="hide" id="table2">
	<tr><td>Table 2</td><td></td><td></td><td></td><td></td></tr>
	<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>
<table class="hide" id="table3">
	<tr><td>Table 3</td><td></td><td></td><td></td><td></td></tr>
	<tr><td></td><td></td><td></td><td></td><td></td></tr>
</table>