New method (24.08.2022)
Form element now has a requestSubmit()
method, which would trigger submit event by itself without workarounds, as stated in submit()
MDN docs:
The HTMLFormElement.submit()
method submits a given <form>
.
This method is similar, but not identical to, activating a form's
submit <button>
. When invoking this method directly, however:
The HTMLFormElement.requestSubmit()
method is identical to activating a form's submit <button>
and does not have these differences.
However, this method is not supported well enough on IE and Safari 15.6. As of 02.09.2022, this is about 76.49% global usage. If you need a more browser-compatible solution, keep reading until the end.
No need to use ref
s
Every answer I've yet seen uses refs when you actually don't need them. Most (if not all) of the form controls have a reference to a parent form in their form
property:
textarea.form.requestSubmit();
Just make sure to attach a handler on one of the form controls, for example: <button>
, <input>
, <textarea>
, <select>
, <option>
.
With all that said, you can write your handlers like that:
<form onSubmit={this.sendMessage}>
<textarea onKeyPress={this.textareaKeypress}/>
</form>
sendMessage: function(event) {
console.log(event);
event.preventDefault();
},
textareaKeypress: function(event) {
if (event.which == 13 && !event.shiftKey) {
event.target.form.requestSubmit();
}
},
Or if you care about browser compatibility, dispatch an event manually (thanks to Karol Dabrowski answer):
textareaKeypress: function(event) {
if (event.which == 13 && !event.shiftKey) {
event.target.form.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
}
},