Basically what I'm trying to do is conditionally show a section of a form. If an input field has either nothing or 0 as inputted, the section is hidden. Otherwise, I want the section to be displayed. While the section does appear when I input numbers in the correct field, it doesn't disappear after I remove the input.
So far, I've tried changing the event listener to listen to the busmiles
variable after moving it outside of the function, but that results in the the section never displaying. I'm not sure what's causing this problem either since I'm not very experience in javascript.
HTML file
<label for="weeklybus">On average, how many miles do you take the bus/train in a week?</label><br>
<input name="weeklybus" id="weeklybus" type="number" required>
<br id="oppositeform">
<div id="busmodeform">
<p>Do you typically take the bus, light rail, or heavy rail?</p>
<input name="busmode" id="bus" type="radio" value="bus">
<label for="bus">Bus</label><br>
<input name="busmode" id="light" type="radio" value="light">
<label for="light">Light rail</label><br>
<input name="busmode" id="heavy" type="radio" value="heavy">
<label for="heavy">Heavy rail</label><br>
</div>
Javascript
function showFormSection() {
var busmiles = document.getElementById('weeklybus').value;
const busmode = document.getElementById('busmodeform');
const extralinebreak = document.getElementById('oppositeform');
if (busmiles != "" && busmiles != "0") {
busmode.style.display = 'block';
extralinebreak.style.display = 'hidden';
} else if (busmiles == "") {
busmode.style.display = 'hidden';
extralinebreak.style.display = 'block';
}
}
window.addEventListener('input', showFormSection);
EDIT: Fixed. Changed from hidden --> none.
CodePudding user response:
You have not declared a "style=" attribute in your DIV element. Too the DIV style should have a property set for "visibility".
<script>
// goes in head
function hideDiv(){
document.getElementById("busmodeform").style.visibility="hidden";
}
</script>
<div id="busmodeform" onblur="hideDiv();" style="visibility:visible;">