Javascript Show Hide Div on Select Option Example; In this tutorial you will learn how to show or hide a Div when a Select option is Selected using JavaScript.
In Js to show a div element when a select option is selected, we can use the onchange event and set the div’s display property to block.
HTML Code:
Here is the HTML part:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<style>
#box {
display: none;
}
</style>
<body>
<select onchange="toggleDiv()">
<option value="0">Select Option</option>
<option value="1">Javascript</option>
</select>
<div id="box">This is the Javascript</div>
</body>
</html>
Javascript Code: here is the related JavaScript code
<script>
function toggleDiv(e) {
const box = document.getElementById('box');
box.style.display = e.target.value == 1 ? 'block' : 'none';
}
</script>
Hope this example help you.