How can i make a html textbox invisible and then it becomes visible when a user clicks on a button?
That button already has a js funtion to get values from an API but can it also make a textbox visible?
Btw i'm using getElementh by id.
The textbox is <input type="textbox" id="city">
Thanks
Asked
Active
Viewed 1,588 times
0

Cereais
- 35
- 1
- 9
-
Welcome to Stack Overflow! Visit the [help], take the [tour] to see what and [ask]. Please first ***>>>[Search for related topics on SO](https://www.google.com/search?q=javascript+toggle+field+button+click+site%3Astackoverflow.com)<<<*** and if you get stuck, post a [mcve] of your attempt, noting input and expected output using the [`[<>]`](https://meta.stackoverflow.com/questions/358992/ive-been-told-to-create-a-runnable-example-with-stack-snippets-how-do-i-do) snippet editor. – mplungjan Nov 04 '21 at 11:47
-
`document.getElementById("city").hidden = someBoolean` where someBoolean will hide if true and show if false – mplungjan Nov 04 '21 at 11:49
-
1Does this answer your question? [Hide and show a text field](https://stackoverflow.com/questions/14578908/hide-and-show-a-text-field) – TAHA SULTAN TEMURI Nov 04 '21 at 11:50
2 Answers
1
Assuming you have set display of your textbox to block, you can simply do if using onclick:
<button onclick="showHideTextBox()">Click Me to Show/Hide</button>
<input type="textbox" id="city">
<script>
function showHideTextBox(){
var x = document.getElementById("city");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Instead of block you can add whatever display attribute value you want to add and inside showHideTextBox function you can add other logic which is needed for your api calls.
I found great answer about how to show hide elements in javascript: How to show or hide an element:

Himanshu Raval
- 790
- 7
- 19
-
that is so inelegant and error prone if the display is not already set – mplungjan Nov 04 '21 at 11:53
-
1
0
Yes, That button can also make the textbox visible. Add textbox's visible code to the button's event listener's function along with your existing fetch API function.
const button = document.getElementById("button");
button.addEventListener("click", function(){
// write textbox's show/hide function
// call your existing function
})
To show/hide textbox you can toggle a class.

Hasan Mobarak
- 133
- 2
- 12