StockDC2 StockDC2 - 7 months ago 18
HTML Question

Two Buttons Within Form

there seems to be some weird behavior with two buttons within my form. Whenever the 'Add Address' button is clicked, the event handler executes properly but after it's finished, it also executes the 'Submit' button's event handler as well.

The code for the buttons is as follows:

<button class="btn btn-success" id="add-address">Add Address</button>
<button type="submit" class="btn btn-default">Submit</button>


I can get around this problem by changing the first button into a
span
element Eg:

<span class="btn btn-success" id="add-address">Add Address</span>


Everything works fine once this change is made. Can someone please explain this behavior? Thanks in advance.

Answer

By default all button elements are submit buttons. You need to add type="button" to the first one to stop it raising a submit event on the parent form element on click.

<button type="button" class="btn btn-success" id="add-address">Add Address</button>
<button type="submit" class="btn btn-default">Submit</button>