-1

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>
f-CJ
  • 4,235
  • 2
  • 30
  • 28
Ven Nilson
  • 969
  • 4
  • 16
  • 42
  • in the textarea **enter** key means a new line, you can override the default behavior and can make **shift + enter** a new line so that on **enter** form is submitted. refer this [link](https://stackoverflow.com/questions/8934088/how-to-make-enter-key-in-a-textarea-submit-a-form) – saurabh Apr 27 '19 at 08:56

3 Answers3

0

Try it like this:

document.getElementById('textarea').addEventListener("keyup", function(event) {

if (event.keyCode === 13) {

  event.preventDefault();

  // do your thing here
  document.getElementById('form').submit();

  document.getElementById('testId').innerHTML = "it works!!!!"; // test

}


});
<!DOCTYPE html>
<html>
<body>
  
<form id="form" name="form" action="/your_page.aspx">
   <label><textarea id="textarea" name="message" placeholder="Type Here"></textarea></label>
</form>
  
<p id="testId"> </p>

</body>
</html>
0

The form tag needs to have an action, or else the form.submit() won't do anything.

<form id="form" name="form" action="/action_page.php" method="get">
    <label>
    <textarea id="textarea" name="message" placeholder="Type Here"></textarea></label>
  <input type="submit">
</form>

This JS will call submit when pressing enter

let form = document.getElementById('form')
form.addEventListener('submit', submitForm);

document.getElementById('textarea').addEventListener('keypress', (event) => {
    if (event.which == 13 || event.keyCode == 13) {
        event.preventDefault()
        form.submit()
    }
});

But the real problem is that form.submit() will not raise the onSubmit event! So your eventHandler won't be called when you sumbit the form programmatically.

From MDN

The submit event only fires when the user clicks a submit button ( or ) in a form. The event is not raised when calling the form.submit() method directly.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

Kokodoko
  • 26,167
  • 33
  • 120
  • 197
  • `form.submit()` will perform default form behavior i.e. redirect to page. Do we prevent default behavior? – Ven Nilson Apr 27 '19 at 09:09
  • Since `form.submit()` does not fire an event, we cannot use `preventDefault()`. But the question is, why do you even use submit, if you don't want to submit the form? If you don't want to submit the form, you can just use a normal button instead of a submit button, and process the textarea however you want when the enter key is pressed. – Kokodoko Apr 27 '19 at 09:26
  • I would suggest leaving out the form tag entirely, and just use javascript to process what is happening in the text field. If the enter key is pressed, you can call an AJAX function to send the data somewhere. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – Kokodoko Apr 27 '19 at 09:34
0

You could set a variable to determine if the form is allowed to submit.

var allow_submit = false;

And modify the form's submit event handler so that event.preventDefault() is called if the allow_submit variable isn't true:

document.getElementsByTagName("form")[0].addEventListener("submit", function(event) {
  if (allow_submit !== true) {
    event.preventDefault();
  }
  // the form is allowed to submit, do stuff
});

Then listen for a keyup event (on the textarea) and if the enter key (keycode 13) was pressed, set allow_submit to true and submit the form:

document.getElementsByTagName("textarea")[0].addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
    allow_submit = true;
    document.getElementsByTagName("form")[0].submit();
  }
  // enter key wasn't pressed, do other suff
});

NOTE: you might have to make the allow_submit variable a global variable, you can do so by replacing var with window., like this:

window.allow_submit = true;

NOTE: you should store the form and textarea elements in a variable, if you're going to use them a lot.

Good luck.

Malekai
  • 4,765
  • 5
  • 25
  • 60
  • This doesn't work, because the submit event handler is not called when using `form.submit()` – Kokodoko Apr 27 '19 at 09:24
  • It appears I've made a mistake, in the second block of code I wrote: `document.getElementsByTagName("textarea")[0].submit();` instead of `document.getElementsByTagName("form")[0].submit();`. Have you changed it? If not, I've edited my answer and you should try again. – Malekai Apr 27 '19 at 09:25
  • Also, your example code doesn't contain a variable declaration for `form`, what is the value of that variable? Are you sure you're selecting the right element? – Malekai Apr 27 '19 at 09:26
  • The real problem is that `form.submit()` does not fire a `submit event`. So the `eventListener` cannot catch this event and then prevent it. – Kokodoko Apr 27 '19 at 09:28
  • Why not? Is it the Markup or JavaScript? – Malekai Apr 27 '19 at 09:29
  • Sadly it's default browser behaviour, you can read it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event – Kokodoko Apr 27 '19 at 09:30
  • 1
    Could you use Ajax? If so, you could remove the textarea from the form and when enter is pressed you could create a GET/POST request to the form's action. – Malekai Apr 27 '19 at 09:31
  • 2
    Yes, the best solution would be to call an AJAX function when enter is pressed in the textarea, and leave out the form tag, and form action entirely. – Kokodoko Apr 27 '19 at 09:37
  • I'm glad you solved the problem, good luck with your project. – Malekai Apr 27 '19 at 09:48