Search code examples
jqueryreload

Page reloading when using jQuery?


So I am currently trying to code my page to allow hidden divs to appear based on pressing buttons. I know that my code works, the first button pressed shows the hidden div. But when I press the second button it momentarily displays and then reloads the page. I don't want it to reload.

 <script>
        $(document).ready(function () {
            $(".button1").click(function () {
                $(".new-post-mid").css("display", "block");
            });
        });
    </script>
    <script>
        $(document).ready(function () {
            $(".button2").click(function () {
                $(".new-post-mid2").css("display", "block");
            });
        });
    </script>
    </div> <!-- navbar -->
    <div class="new-post-outer">
        <div class="new-post-outish">
            <button class="button1">Edit your account details</button>
            <li> Fields marked with an asterisk (*) are required.</li>
        </div>
        <div class="new-post-mid">
            <form class="abc">
                <label> Please enter your password to change your settings.</label>
                <label> Password: </label>
                <label> Repeat Password: </label>
                <label> Please complete the captcha: </label>
                <button class="button2">Submit</button>
            </form>
        </div>
        <div class="new-post-mid2">
            <form class=abc>
                <label> Username: (*) </label>
                <label> Email Address: (*) </label>
                <label> First Name: </label>
                <label> Last Name: </label>
            </form>
        </div>
    </div><!-- new-post-outer-->

Solution

  • Just use e.preventDefault() or as mentioned by @Tyler Roper in the comments, you can just change the button to <input type="button ... />"

    The issue you are facing caused by the button control handling the submit action of the form.

       ...
       $(document).ready(function () {
            $(".button2").click(function (e) {
                e.preventDefault()
                $(".new-post-mid2").css("display", "block");
            });
        });
        ...