In my current HTML form generated by PHP, I have multiple instances of the following structure:
function show(elem, show){
var elements =
elem.parentNode.parentNode.parentNode.getElementsByClassName("hidden");
var i;
for(i=0; i<elements.length; i++){
if(show){
elements[i].style.display = "initial";
}
else{
elements[i].style.display = "none";
}
}
}
.hidden {
display: none;
width: 100%;
padding: 0px;
margin: 2px;
overflow: hidden;
}
<fieldset>
<legend>Something</legend>
<ul>
<li>
<input type="radio" name="X" value="No" onchange="show(this, false)">
<label>No</label>
</li>
<li>
<input type="radio" name="X" value="Yes" onchange="show(this, true)">
<label>Yes</label>
</li>
</ul>
<p class="hidden">
Elements
</p>
<fieldset class="hidden">
Elements
</fieldset>
</fieldset>
The goal is to show the class="hidden"
elements when Yes is checked and hide them when No is checked, with them being hidden by default.
The issue arises when the form's status is loaded from a database and "Yes" can be pre-checked (in which case the corresponding html would be
<input type="radio" name="X" value="Yes" ...
). This requires an onload function, possibly using jQuery, to check if Yes is selected on load and then display the hidden elements. However, as my web design skills are limited, I am unsure how to proceed.
I acknowledge that my JavaScript and overall design may be messy, so any suggestions for improvement would be greatly appreciated.
EDIT
Following Joey Pinto's advice, here is the final implementation (including additional JavaScript):
$(document).ready( function(){
var show=document.getElementsByClassName("shower");
for(i=0;i<show.length;i++){
if(show[i].checked){
mostrar(show[i],true);
}
}
}
);
Additionally, the radio input for "Yes" has been assigned the class="shower"
.