I'm facing a problem, What I'm doing is there is a <form>
which has a <textarea>
. What I want to achieve is when the user press the Enter
key
on textarea
then the form is submitted.
The default form is attached with an eventListener
submit
and execute a callback function.
But the problem is I want to execute that callback on Enter
key.
I know I could achieve that same behavior by using JQuery .submit(callback)
method.
But is there a way in Vanilla javascript re-trigger the same callback function.
const submitForm = (event) => {
event.preventDefault();
alert('form is submitted!');
};
// Form Event
document.getElementById('form').addEventListener('submit', submitForm, false);
// Key Event
document.getElementById('textarea').addEventListener('keypress', (event) => {
if (event.which === 13 || event.keyCode === 13) {
event.preventDefault();
// Form submit
}
}, false);
* {
box-sizing: border-box;
}
textarea {
width: 380px;
min-height: 210px;
padding: 18px;
font-size: 26px;
margin-bottom: 16px;
resize: vertical;
}
<form id="form" name="form">
<label>
<textarea id="textarea" name="message" placeholder="Type Here"></textarea>
</label>
</form>