Annie C
Annie C

Reputation: 804

2 buttons on form only 1 with submit type but both triggers submit event

Not using jQuery, just plain javascript with DOM. There are 2 buttons on the form, one has no type, one has type="submit"

Here is an example of my question:

https://plnkr.co/edit/wAlpawx2wJUZ9FXWXL9h?p=preview

         <div>
            <button class="add">add</button>
        </div>
        <div>
            <button type="submit">submit</button>
        </div>

both buttons trigger the submit event. how do I get only the button with type="submit" to trigger the submit event?

Also, how do I persist the form data so that the result can stay in the "pre" tag when the submit is triggered?

Upvotes: 4

Views: 1042

Answers (4)

Prusprus
Prusprus

Reputation: 8065

As per specifications:

The missing value default is the Submit Button state.

If the type attribute is in the Submit Button state, the element is specifically a submit button.

W3C documentation

Upvotes: 1

TerryTurcotte
TerryTurcotte

Reputation: 41

you only need to change the type of the button that you don't want to submit with "button". I know it feels weird, but the default type of a button tag is "submit".

<button type="button">Add</button>

Upvotes: 4

Thomas Wolfe
Thomas Wolfe

Reputation: 638

The default type of a button inside a form is submit. You need to set type="button" if you want to prevent it from triggering the form submit.

See this question for more details.

Upvotes: 3

Steve
Steve

Reputation: 2046

set the type attribute to "button" or manually cancel the event

<button type='button' class='add'>add</button>

-or-

$('button.add').click(function(e){
    e.preventDefault(); // cancel default behavior
    // my add logic
});

Upvotes: 4

Related Questions