The buttons do not have 'default action'. Although they may cause a form submission if it belongs to a form
and is marked with attribute type="submit"
instead of type="button"
Here is a small example of a form with two buttons, one marked as submit
and another as button
. Both will send the form. One of them natively, and another programmatically.
We also take the opportunity to see the operation of preventDefault
, which in this case applies to prevent the sending of the form by the traditional method.
(function() {
var form = document.getElementById('myform');
function onSubmit(event) {
// Prevenimos el envio del formulario.
if (event) { event.preventDefault(); }
console.log('submitted');
}
form.addEventListener('submit', onSubmit, false);
form.submit = onSubmit; // Notese que obSubmit queda anclado a form.submit, no a button.click
console.log(urlEncodeFormData(form));
function urlEncodeFormData(form) {
var i, e, data = [];
for (i = 0; i < form.elements.length; i++) {
e = form.elements[i];
if (e.type !== 'button' && e.type !== 'submit') {
data.push(encodeURIComponent(e.id) + '=' + encodeURIComponent(e.value));
}
};
return data.join('&');
}
})();
<form id="myform">
Name: <input id="name" type="text" value="dperezv" /><br />
Email: <input id="email" type="text" value="[email protected]" /><br />
<br />
<button type="submit">type=submit</button>
<button type="button" onclick="form.submit()">form.submit()</button>
</form>