0

I have a textarea that submits when the input field is not empty. Assuming I want to prevent multiple submission on pressing the enter key simultanouesly with the following, it only submits each time I refresh the page. this is the code:

window.formWasSubmitted = false;

    document.getElementById('new-input').addEventListener('keyup', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13 && $.trim($(this).val()) && !window.formWasSubmitted) { // enter key press     && $(this).val().length > 0
            e.preventDefault();
            window.formWasSubmitted = true;
            send();
        }
        //window.formWasSubmitted = false;
    });

please how can I allow the textarea to submit without refreshing the page on entering data each time

1 Answers1

0

Your question isn't very clear, but it sounds like you want to debounce the enter key. Is that correct? Since you're using JQuery, take a look at this: Debounce function in jQuery

Community
  • 1
  • 1
adam0101
  • 29,096
  • 21
  • 96
  • 174
  • yes. I want to debounce the enter key after the first time – user6731422 Nov 03 '16 at 19:12
  • Then I believe all you need to do is get rid of the `window.formWasSubmitted` code and change `send();` to `$.debounce(250, send);` – adam0101 Nov 03 '16 at 19:23
  • If I press the enter key simultaneously three times, it sends the contents three times, so it does not debounce – user6731422 Nov 03 '16 at 19:40
  • OK, I think you have to assign the result of the debounce function to a variable like `var sendDebounced = $.debounce(250, send);` OUTSIDE of the event handler and then inside the event handler you'd use `sendDebounced();`. – adam0101 Nov 04 '16 at 20:19