Issue
I’m still very new to html css and JS. I am trying to make an input field appear/toggle from a button click. here is my code so far.
HTML
<form>
<fieldset>
<legend>Competency 15 Event Listeners</legend>
<ol>
<li><button type="text" id="theButton" onclick="clickMe()">Click me!</button></li>
<li><input type="text" name="popup" id="popup"></li>
</ol>
</fieldset>
</form>
CSS
form{
width: 50%;
}
#popup {
display: none;
}
JavaScript
function clickMe(){
var text = document.getElementById("popup");
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
I’ve looked all around the internet and can’t seem to find the answer. Thanks in advance
Solution
<form>
<fieldset>
<legend>Competency 15 Event Listeners</legend>
<ol>
<li><input type="button" value="click here" onclick="clickMe()"></li>
<li><input type="text" id="show"></li>
</ol>
</fieldset>
</form>
<script>
function clickMe() {
var text = document.getElementById("show");
if (!text.style.display) {
text.style.display = "none";
}
if (text.style.display === "none") {
text.style.display = "block";
} else {
text.style.display = "none";
}
}
</script>
form{
width: 50%;
}
#show {
display: none;
}
If you use fieldsets, you should use input with a type button to make buttons. I have changed your button to an input with a type button and now it works.
Also, added another if loop that checks if there is a display property and if it is empty "", it sets it to "none". Without the first if loop it will take 2 clicks to show the input, because first you will need your else to set display to "none" and only the second click will set it to "block".
I dont remember why does it work like that, but its just how CSS functions, if you feel like it, use console.log(text.style) to get a full CSS Object and examine it.
Answered By – Gerpstarg
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0