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:
<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?
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?
Share Improve this question asked Jun 30, 2016 at 1:11 Annie CAnnie C 8042 gold badges14 silver badges32 bronze badges 1- 3 Buttons by default inside of a form trigger the submit. For the second button (that you don't want to submit) you need to prevent the default action from occurring, which is to submit. – Sterling Archer Commented Jun 30, 2016 at 1:14
4 Answers
Reset to default 4set 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
});
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>
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.
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