Let’s say you create a wizard in a HTML form. One button saves the data and goes back; the other saves and navigates forward.
Since the back button appears first in the markup, it will be used when we press Enter
.
However in this case we want the second button to be the default. Now we have three different options:
- Add a hidden submit button with the same action first (☹️ duplication)
- Put the desired submit button first and move it to the correct place via CSS (☹️ may not be feasible, may result in cumbersome styling)
- Change the handling of the return key in all form inputs via JavaScript (☹️ needs javascript)
None of the options are ideal. We choose the 3rd because most browsers have JavaScript enabled. Here the code to adapt the behavior:
document.addEventListener('DOMContentLoaded', (ev) => {
for (const defaultSubmitInput of document.querySelectorAll('[data-default-submit]')) {
const surroundingForm = defaultSubmitInput.form;
for (const formInput of surroundingForm.querySelectorAll('input')) {
if (formInput.dataset.ignoreDefaultSubmit != undefined) { continue; }
formInput.addEventListener('keypress', (ev) => {
if (ev.keyCode == 13) {
ev.preventDefault();
// if we would use surroundingForm.submit(),
// the submit button's name & value would not sent as part of the post data
// however, this might be required by the backend code
defaultSubmitInput.click();
}
})
}
}
});
And here the HTML markup:
<!-- example markup -->
<form action="https://postman-echo.com/get" method="get">
<input type="text" name="field1">
<input type="submit" name="submit" value="other action">
<input type="submit" name="submit" value="default action" data-default-submit> <!-- used when enter key is pressed -->
</form>
Happy Coding!
Resources
- Original Stackoverflow Question
- Example CodePen