0

I have a bunch of forms on a page that each contain an html textarea:

<textarea name="Comment" class="inputTextArea">Hello World!</textarea>

I have javascript event handler that submits the form when the user presses Enter:

$(".inputTextArea").keypress(function (e) {
    if (e.which === 13 && !e.shiftKey) {
        $(this).closest("form").submit();
        e.preventDefault();
    }
});

The javascript does submit the form on Enter, but the submitted data does not contain the current contents of the textarea.

If I set a breakpoint on the call to submit() and look at the contents of "this" (which is the textarea), the innerHTML shows the initial textarea's contents (i.e., "Hello World!") rather than the text that is currently in the textarea (e.g., "Goodbye World!").

Is there something I need to do to update the textarea control's contents before submitting it?

Thanks!

SOLUTION (or "CAUSE" or "<blush>")

My forms have two submit buttons, so my call to $(this).closest("form").submit() wasn't selecting the button I expected (a "Save" button). When the form was posted, I wasn't saving the posted data and thought the textarea hadn't been updated—that wasn't the case.

My solution was to make sure the correct button was clicked when Enter was pressed.

var buttons = $(this).closest('form').find(':submit');
buttons[0].click();

Embarrassingly, this topic, and its title, have nothing to do with the problem or solution, but maybe my clumsy path to a solution will help someone else.

Steve A
  • 1,798
  • 4
  • 16
  • 34
  • 1
    Typing in a textarea doesn't change `.innerHTML`, it changes `.value`. You don't have to update the contents, you should just be able to submit it. – James Apr 14 '21 at 19:31
  • James, knowing that the .value, not the .innerHTML, changed quickly exposed the problem (i.e., I could see that the .value **had** changed). – Steve A Apr 15 '21 at 15:28

1 Answers1

1

In the provided code it should work perfectly, the issue might be in form

$(".inputTextArea").keypress(function (e) {
    if (e.which === 13 && !e.shiftKey) {
        $(this).closest("form").submit();
        e.preventDefault();
    }
});
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

<form >
<textarea name="Comment" class="inputTextArea">Hello World!</textarea>
  <button type="submit" class="btn btn-primary submit-btn">Submit</button>
</form>
  • Yes, Adeeb, the issue was in the form. I had two submit buttons. I edited my initial post to expose the problem. – Steve A Apr 15 '21 at 15:27