I've carried around a really useful JavaScript function for a while, not entirely sure of the origin (probably here on Stack Overflow) but it's certainly not something I've written as I know very little JS.
It basically reveals form sections based on the chosen select option. It works a charm when used once, however I'm now in a situation whereby I have a fairly complex form and need to use it multiple times. The obvious method is to copy\paste and simply rename each function thus making it unique. However, that's a lot of replicated code.
My issue is if I re-use it, the two select fields interfere with each other. I've tried seeing if I can lock it down or it isolate is using an ID but I'm struggling.
Minimum, reproducible example:
var current;
function reveal(element) {
if (current !== undefined) {
var chosen = document.getElementById(current);
chosen.classList.remove("visible");
chosen.classList.add("hidden");
}
var fetchMe = element.options[element.selectedIndex].getAttribute('data-show');
if (fetchMe !== null) {
current = fetchMe;
var fetched = document.getElementById(fetchMe);
fetched.classList.remove("hidden");
fetched.classList.add("visible");
}
}
.hidden {
display: none;
}
.visible {
display: block;
}
<h2>Knowledge</h2>
<select onchange="reveal(this)">
<option>Select...</option>
<option data-show="known">Known</option>
<option data-show="unknown">Unknown</option>
</select>
<div class="hidden" id="known">
<input type="text" name="known" value="Known">
</div>
<div class="hidden" id="unknown">
<input type="text" name="unknown" value="Unknown">
</div>
<h2>Superheroes</h2>
<select onchange="reveal(this)">
<option>Select...</option>
<option data-show="batman">Batman</option>
<option data-show="superman">Superman</option>
</select>
<div class="hidden" id="batman">
<input type="text" name="batman" value="Batman">
</div>
<div class="hidden" id="superman">
<input type="text" name="supermann" value="Superman">
</div>
Ideally I want to be ringfence it, or use an ID to limit it.
Also available as a Fiddle.