jQuery

How to show/hide DIV on selection of ANY drop-down value?

In this tutorial, we are going to see how to show/hide DIV on selection of ANY drop-down value? The following example shows how to show and hide div blocks based on a drop-down list using jQuery’s change() method in combination with show() and hide() methods. The div blocks in the following example are hidden by default using the CSS “display” property, which is set to “none”.
 

How to show/hide DIV on selection of ANY drop-down value?
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>show/hide DIV on selection of ANY drop-down value</title>
		<style type="text/css">
			.msg{
				margin-top: 25px;
				padding: 25px;
				display: none;
				color: #fff;
			}
			.yellow{ 
				background: yellow; 
			}
			.green{ 
				background: green; 
			}
			.red{ 
				background: red; 
			}
		</style>
		<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("select").change(function(){
            $(this).find("option:selected").each(function(){
                var val = $(this).attr("value");
                if(val){
                    $(".msg").not("." + val).hide();
                    $("." + val).show();
                } else{
                    $(".msg").hide();
                }
            });
        }).change();
    });
    </script>
	</head>
	<body>
    <select>
        <option>Choose color</option>
        <option value="yellow">Yellow</option>
        <option value="red">Red</option>
        <option value="green">Green</option>
    </select>
		<div class="yellow msg">You have selected Yellow</div>
		<div class="red msg">You have selected Red</div>
		<div class="green msg">You have selected Green</div>
	</body>
</html>
Result
You have selected Yellow
You have selected Red
You have selected Green
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to show/hide DIV on selection of ANY drop-down value?

  • pooja sharma

    if we want to show first value of div by default than what will the code change please help

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *