I am using this Jquery toggle script, which selects particular buttons to show/hide particular tables of information on the same page. This shows only 2 buttons; there are as many as 20 or so on the page. This code works fine:
(Explanation of “bag1” in the code: “Bag 1” describes the content inside a model kit’s Bag 1, and the button btnbag1x will show-hide a table listing of clickable contents of Bag 1. It is kept initially hidden to limit scrolling.)
You can bind an event listener to all buttons which have an ID starting with btnbag, and strip the btn part to toggle the corresponding element like
$('[id^="btnbag"]').click(function() {
var id = this.id.replace(/^btn/, '')
$('#' + id).toggle()
})
although it would be safer to add a dedicated class to those buttons, like say
$('.toggle-btn').click(function() {
var id = this.id.replace(/^btn/, '')
$('#' + id).toggle()
})
Performance-wise this is still not ideal though as it means a lot of redundant DOM queries – each time you click the button, the corresponding element has to be searched anew. So you might map the element references to the button IDs beforehand, like
var toggleMap = {}
$('.toggle-btn')
.each(function() {
var id = this.id.replace(/^btn/, '')
toggleMap[this.id] = $('#' + id)
})
.click(function() {
toggleMap[this.id].toggle()
})