Today I Learned - Rocky Kev

TIL another way to prevent buttons from submitting HTML

POSTED ON:

TAGS:

Here's a standard form.

Hit that button, the console displays that message.


<form id="say-hi">
<button>Activate Me</button>
</form>

<script>
let form = document.querySelector('#say-hi');
form.addEventListener('submit', function () {
console.log('Someone said hi!');
});
</script>

What happens when you have two buttons? Maybe you'll use a conditional and event.preventDefault() to stop it.


<form id="say-hi">
<button>Activate Me</button>
<button id="toggle-something">Toggle Something</button>
</form>

<script>
form.addEventListener('submit', function (event) {

// Ignore the #toggle-something button
if (event.submitter.matches('#toggle-something')) {
event.preventDefault();
}

console.log('Someone said hi!');

});

</script>

Another way is just to add type="button"

<form id="say-hi">
<button>Activate Me</button>
<button id="toggle-something" type="button">Toggle Something</button>
</form>

Now "Activate Me" will trigger the submit, where the Toggle Something will be ignored.

Woot! Less Javascript!

via How to prevent buttons from causing a form to submit with HTML


Related TILs

Tagged:

TIL another way to prevent buttons from submitting HTML

When you have two buttons, you can use 'type=button' to stop them from submitting a form.

TIL another way to prevent buttons from submitting HTML

When you have two buttons, you can use 'type=button' to stop them from submitting a form.

TIL another way to prevent buttons from submitting HTML

When you have two buttons, you can use 'type=button' to stop them from submitting a form.