How to show/hide DIV if checkbox selected
In this tutorial, we are going to see how to show/hide DIV if checkbox selected. The following example explains how to show and hide div blocks based on the checked checkbox using jQuery’s toggle() method. 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 if checkbox selected
<!DOCTYPE html> <html> <head> <title>How to show/hide DIV if checkbox selected</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(){ $('input[type="checkbox"]').click(function(){ var val = $(this).attr("value"); $("." + val).toggle(); }); }); </script> </head> <body> <input type="checkbox" name="color" value="Yellow"> Yellow <input type="checkbox" name="color" value="Red"> Red <input type="checkbox" name="color" value="Green"> Green <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 |
---|
Yellow
Red
Green
You have selected Yellow
You have selected Red
You have selected Green
|