简体   繁体   中英

Show/Hide div with Dropdown Option

Relatively new to JS, need some help in getting a div to hide/show properly based on a dropdown choice.

If dropdown='no', div should be hidden. If dropdown='yes', div should show. I got the JS to work correctly at first, but once the form saves and I reopen it, the div disappears. I believe I've written the JS wrong by telling the div to show only on change. But I'm too new to know - help!

 $('.analysisPub').on('change', function() { if (this.value === "Yes") { $("#analysis").show(); } else { $("#analysis").hide(); } }); 
 .analysis { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>Does this publication include analysis in any form?</td> <td class="analysisPub" id="analysisPub" name="analysisPub"> <select> <option value>Yes</option> <option value>No</option> </select> </td> </tr> </table> <div id="analysis" class="analysis"> <table> <tr> <td>Test Name</td> <td>Test 1</td> <td>Test 2</td> </tr> </table> </div> 

There were two main mistakes in your code. They are as follows -

1st - you were targetting the <td> rather than the <select>

2nd - your dropdown options were not having values

I've fixed them now. It works as u mentioned in the description.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('#dropdownAnalysis').on('change', function() { if (this.value == 'Yes') { $("#analysis").show(); } else { $("#analysis").hide(); } }); }); </script> <table> <tr> <td>Does this publication include analysis in any form?</td> <td class="analysisPub" id="analysisPub" name="analysisPub"> <select id="dropdownAnalysis"> <option value="Yes">Yes</option> <option value="No">No</option> </select> </td> </tr> </table> <div id="analysis" class="analysis"> <table> <tr> <td>Test Name</td> <td>Test 1</td> <td>Test 2</td> </tr> </table> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM