forrest
forrest

Reputation: 10972

Why does jQuery "toggle" button trigger the Submit button on a form?

I have built a fairly complex form which includes a hidden section that the user can toggle open for entering more information if necessary. However, when you click on this toggle button labeled I have more Nativities, it triggers the submit button and prematurely submits the form.

The form is in dev right now, but it can be found here.

The code I am using for the toggle button is:

<script type="text/javascript">
    $(function() {
        $("#schedule").accordion({ header: "h5", collapsible: true });
        $("#more-nativities").hide();
        $("#toggle").click(function()   {
            $("#more-nativities").slideToggle("slow");
        });
    });
    </script>

The code for the submit button is pretty basic:

<input id="submit2" type="image" src="_images/btn_register.jpg" name="submit"  alt="" onmouseover="javascript:this.src='_images/btn_register2.jpg'" onmouseout="javascript:this.src='_images/btn_register.jpg'"/>

The code for the toggle button is:

<button id="toggle">I have more nativities</button>

Any ideas as to why the toggle button is triggering the submit? And more importantly how to solve the problem?

Thanks!

Upvotes: 6

Views: 3918

Answers (4)

Raffael Luthiger
Raffael Luthiger

Reputation: 2211

Esteban has one solution. A better one is described in the jQuery tutorial:

 $(document).ready(function(){
   $("a").click(function(event){
     alert("As you can see, the link no longer took you to jquery.com");
     event.preventDefault();
   });
 });

Upvotes: 2

Chris Laplante
Chris Laplante

Reputation: 29658

From W3Schools:

Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".

http://www.w3schools.com/tags/tag_button.asp

Be sure to specify type="button"

Upvotes: 1

n00dle
n00dle

Reputation: 6043

Try adding a type, i.e.:

<button type="button" id="#toggle">Text</button>

http://www.w3schools.com/tags/tag_button.asp says this should be always defined. It's possible the browser is defaulting to a submit button.

Upvotes: 12

Esteban Araya
Esteban Araya

Reputation: 29664

Try

 return false;

after the slide toggle on the click function fro the toggle button.

Upvotes: 1

Related Questions