Inside this article we will see the concept i.e Javascript Show Hide Div on Select Option Example Tutorial. Article contains the classified information about show hide effect (Toggle effect) on HTML element using javascript.
If you are looking for a solution to show and hide an element of HTML using javascript then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.
You can prefer jquery plugin as well. But here we will use the core concept of javascript to implement this toggle effect of an element.
Learn More –
- JavaScript Remove All Event Listeners From an Element
- PHP Program to Count The Number of Vowels in a String
- JavaScript Check if String Contains at Least One Number
- Laravel 9 How To Add Conditional Class in Blade Template
Let’s get started.
Application Programming
Create a file index.html inside your localhost directory. Open file and write this complete code into it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Javascript Show Hide Div on Select Option</title> <style> #box { display: none; background-color: orange; padding: 20px; height: 100px; width: 100px; margin-top: 20px; } </style> </head> <body> <select onchange="toggleDiv(this.value)"> <option value="">Select Option</option> <option value="1">Show Box</option> <option value="0">Hide Box</option> </select> <div id="box"> Visible Box </div> <script> function toggleDiv(value) { if (value == "") { alert("Please select an option"); } const box = document.getElementById('box'); box.style.display = value == 1 ? 'block' : 'none'; } </script> </body> </html>
Code Explanation
On change event on select dropdown element.
<select onchange="toggleDiv(this.value)">
...
</select>
Whenever we select an option from dropdown, it sends selected option value to toggleDiv function.
Create Box ID reference for Div element
const box = document.getElementById('box');
Show Hide toggle effect on the basis of 1 (Show) and 0 (Hide) value
box.style.display = value == 1 ? 'block' : 'none';
Application Testing
Now,
Open project into browser.
URL: http://localhost/index.html
Select Show Box option
Once you select Hide Box option, it will hide the visible box div.
We hope this article helped you to learn Javascript Show Hide Div on Select Option Example Tutorial in a very detailed way.
Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.
If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.