I have a save button at the bottom of a react form. That button is like this:
<button type="button" onClick={saveHandler} disabled={disabled}>Save</button>
The disabled value is true whenever there is validation errors on the form, such as not filling in required fields.
I don't show the error messages on required fields unless you have focused on them, this way the form isn't littered with error messages right from the start.
If a user just jumps down to the bottom of the page, and clicks on the save button, but while it is disabled, I would like it to still call the saveHandler even if the button is disabled. In this case, I will make all the errors appear for the fields that weren't filled in.
Is there a way to make a disabled field trigger an onClick event when you click on it?
You need some sort of wrapper, listen to the click event on the wrapper, and set pointer-events: none
on the disabled buttons CSS (assuming you want this to work in Firefox, pretty sure it works even without it in Chrome). Not in react but to demonstrate:
document.getElementById('wrapper').addEventListener('click', function() { console.log('wrapper'); });
document.getElementById('button').addEventListener('click', function() { console.log('button'); });
document.getElementById('disabler').addEventListener('click', function() { document.getElementById('button').disabled = !document.getElementById('button').disabled});
[disabled] {
pointer-events: none;
}
<label><input type="checkbox" checked id="disabler"/> Disabled</label>
<span id="wrapper"><button id="button" disabled>Click</button></span>