I know this is old, but I wanted to offer my view on this.
What I tend to do, for better or worse, in trying to prevent use of inline 'onclick' code, is the following:
- Assign type="button" to the cancel button within a form, then
- set a href="/wherever_page_needs_to_go" attribute (alt tags, titles, etc. which are not included in the code below),
- set a specific class to the button, e.g. "btn-cancel", so that it can be selected if a specific need requires it (although in the code below the class is not needed for selection, it may be required for css styling, though),
- link to a JavaScript code in a separate file.
Code for btn-events.js (for me generally located in /public/js folder):
// Select all form buttons with href attribute in DOM
const buttons = document.querySelectorAll('form button[href]');
// Add event listeners for selected buttons
buttons.forEach(btn => {
const href = btn.getAttribute('href');
btn.addEventListener('click', evt => window.open(href, target = '_self'));
});
Then in HTML:
<button class="btn-cancel" type="button" href="/wherever">Cancel</button>
Also, in HTML just before the ending body tag, link the script:
<script src="js/btn-events.js"></script>
This method allows me to control some of the other buttons I occasionally have within the form and which do not submit anything but are purely "navigational" in nature.