Search code examples
jqueryformsbuttonback

Hide/Show Back Button


I am working on a form which has a small part that hides and shows a div then submits to a page. My problem is that when I hide the div and submit, then click the back button, the div is not hidden. Here is my code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
    <script type="text/javascript" src="http://nix.lv/history/jquery-1.2.3.min.js"></script>
    <script type="text/javascript">

        jQuery(document).ready(function ($) {

            $('#Contact').change(function () {
                if ($(this).val() == ('Yes')) { $('#sentBy').show(); }
                else { $('#sentBy').hide(); }
            });

        });
</script>
</head>

<body>
<form method="post" action="http://google.com">
<div><p><label for="Contact">Want an answer? </label><br />
                    <select size="1" name="Contact" id="Contact" onchange="toggle('hide', 'sentBy');">
                        <option value="Yes" selected="selected">Yes</option>
                        <option value="No">No</option>
                    </select></p>
                    </div>
    <div id="sentBy">
        this is a test
    </div>
    <input type="submit" value="wow"/>
 </form>
</body>
</html>

Solution

  • On document ready, check the value of the dropdown and hide the div if appropriate. Try this edit:

    jQuery(document).ready(function ($) {
    
            var shouldHideDiv = $('#Contact').val() != 'Yes';
            if (shouldHideDiv) {
                $('#sentBy').hide();
            }
    
            $('#Contact').change(function () {
                if ($(this).val() == ('Yes')) { $('#sentBy').show(); }
                else { $('#sentBy').hide(); }
            });
    
        });