Search code examples
javascriptforms

different behavior with <form> and without <form>


There is the following code:

<div class="my-page">
            <!-- <form id="my-form"> -->
                <h2>Clickable Dropdown</h2>
                <p>Click on the button to open the dropdown menu.</p>
                <fieldset id="my-fieldset">
                    <div class="dropdown">
                        <button onclick="myFunction()" class="dropbtn">1234</button>
                        <div id="File1" class="dropdown-content">
                            <a href="#1">1</a>
                            <a href="#2">2</a>
                            <a href="#3">3</a>
                            <a href="#4">4</a>
                        </div>
                    </div>
                </fieldset>
            <!-- </form> -->
        </div>

If you comment out in it, then everything works correctly. Otherwise the work is wrong

Can someone explain what is wrong here?


Solution

  • A button has by default the type submit. Submit buttons in a form will submit the form, reloading the page.

    If you want to use a button inside a form that does not submit the form, give it type "button" explicitly.

    <button type="button" onclick="myFunction()" class="dropbtn">1234</button>