I've created a questionnaire, which allows users to answer YES or NO to each question. if NO is clicked, field is hidden. But if YES is clicked, I want to show hidden field which has further instructions for each question.
The following code works for the first question, but not for subsequent question.
How can I amend the script to work for all questions on the questionnaire.
function showhideInfo()
{
if (document.getElementById('inlineRadio1').checked) {
document.getElementById('reqdfield').style.display = 'block';
}
else document.getElementById('reqdfield').style.display = 'none';
}
Here is my html code
<div class="input-group">
<b><label class = "label">Have you attended this course before</label></b>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio1" value="YES" onclick="showhideInfo()">
<label class="form-check-label" for="inlineRadio1">YES</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="inlineRadioOptions" id="inlineRadio2" value="NO" onclick="showhideInfo()">
<label class="form-check-label" for="inlineRadio2">NO</label>
</div>
<div class="regdInfo" id="reqdfield" style="display:none">
You will need to provide details of previous course attended.
</div>
</div>
Ids are (supposed to be) unique on a web page. In particular getElementById will return a single element only, even if there were multiple elements having the same ID in the document.
Use a selector based on the class instead. Eg:
document.querySelectorAll('.reqdInfo').forEach ( pe => { pe.style.display = 'none'; /* or 'block' */ });