
How to make textbox visible on button click
As a web developer, you may come across the need to make a HTML textbox visible or invisible with the click of a button. This is easily achievable through JavaScript and its getElementById() method.
Let's say we have an input type of text that has an id attribute set as city. We also have our button element with it's onclick event handler calling showHideTextBox() function when clicked.
<button onclick="showHideTextBox()"> Click Me to Show/Hide </button>
Inside this showhideTextBox() function, we can use document.getElementById("city") to access our html textbox by its ID and then check if display property is none (invisible) or block (visible).
If it's invisible , then set display property as block so that it will be visible. otherwise, if already visible , then hide it by setting display:none .
How to make textbox visible on button click using class#
Another way to achieve the same result is by using CSS classes. You can create a class called hidden and apply it to the textbox element.
Then, you can use JavaScript to add or remove this class on button click to show or hide the input element as needed.
- In the above example, we defined a class hidden. The hidden class is set to hide elements by using the display: none; property.
- An input text element with the id myTextbox is defined and assigned the hidden class initially. A button with the id showButton is also defined.
- A click event listener is attached to the button. When the button is clicked, a function is triggered.
- The function checks if the input text element has the hidden class using the classList.contains() method.
- If the input text element has the hidden class, it is removed using classList.remove(), making it visible. If the input text element does not have the hidden class, it is added using classList.add(), hiding it.
- Clicking the button toggles the visibility of the input text element based on its previous state.