I have put together the following code that will unhide <div>
s if "Override" is selected from the dropdown. The problem I am having is that to select Override, then select another reason, then select override again for it to work as intended.
My goal is to have it unhidden when it gets selected for the first time.
HTML:
<body>
<div class="main">
<div class="row">
<!-- Begin left side data entry -->
<form> <!-- Form tag is only used to allow the Clear button at the bottom to clear the data entry area. -->
<div class="cell" style="vertical-align: top; padding-top: 10px; padding-left: 145px;">
<div class="row">
<div class="cell">1. Reason for Interuption </div>
<label>
<select class="cell" id="Q1" onChange="showQuest(this.value); store_value('Q1',this.value);">
<option value=""></option>
<option value="Call">Call</option>
<option value="Argument">Argument</option>
<option value="Sleep">Sleep</option>
<option value="Override">Override</option>
</select>
</label>
</div>
<div class="row" id="hidden8" style="display:none">
<div class="cell" id="Q8" >8. If Override, Override Approved by </div>
<div class="cell"><input type="text" id="A8" /></div>
</div>
</div>
</form>
</div>
</div>
</body>
JavaScript I have put together:
//function to unhide questions if Override is selected
function showQuest(sel)
{
if (sel == 'Override')
{
document.getElementById('Q1').addEventListener('change', function () {
var style = this.value == 'Override' ? 'block' : 'none';
document.getElementById('hidden8').style.display = style;
document.getElementById('hidden9').style.display = style;
});
}
}
I am not receiving any error messages when I load it into a browser and the code acts the same when I have it in JSFiddle.
Any help would be greatly appreciated.
The first time you call showQuest
, you just add the event listener, and it is called the second time. Take the addEventListener
outside the function:
//function to unhide questions if Override is selected
document.getElementById('Q1').addEventListener('change', function() {
var style = this.value == 'Override' ? 'block' : 'none';
document.getElementById('hidden8').style.display = style;
});
<div class="main">
<div class="row">
<!-- Begin left side data entry -->
<form>
<!-- Form tag is only used to allow the Clear button at the bottom to clear the data entry area. -->
<div class="cell" style="vertical-align: top; padding-top: 10px; padding-left: 145px;">
<div class="row">
<div class="cell">1. Reason for Interuption </div>
<select class="cell" id="Q1">
<option value=""></option>
<option value="Call">Call</option>
<option value="Argument">Argument</option>
<option value="Sleep">Sleep</option>
<option value="Override">Override</option>
</select>
</div>
<div class="row" id="hidden8" style="display:none">
<div class="cell" id="Q8">8. If Override, Override Approved by </div>
<div class="cell"><input type="text" id="A8" /></div>
</div>
</div>
</form>
</div>
</div>