Okay, before asking this question, I was sure there already was an answer on stackoverflow for this... but I can't find anything so here goes:
I'm using flask to create a website. One part of it to is to make comments.
When I click enter, it should submit the form to add a comment to the Database.
Here is my code for that:
(This is the form)
<form method="POST">
{{ form.hidden_tag() }}
{% if form.comment.errors %}
{{ form.comment(id="comment-input", class="new-comment", placeholder="Add a new comment", autofocus="autofocus") }}
<div class="invalid-feedback" style="display: block;">
{% for error in form.comment.errors %}
<span>{{ error }}</span>
{% endfor %}
</div>
{% else %}
{{ form.comment(id="comment-input", class="new-comment", placeholder="Add a new comment", autofocus="autofocus") }}
{% endif %}
{{ form.submit(class="btn btn-outline-info", id="submit", style="display:none;") }}
</form>
And I'm using this javascript to submit the form when the enter key is pressed:
var input = document.getElementById("comment-input");
input.addEventListener("keyup", function(event) {
// Cancel the default action, if needed
event.preventDefault();
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Trigger the button element with a click
document.getElementById("submit").click()
}
});
The problem is, usually if I press enter after typing my comment, it works fine but if I hold down enter after typing my comment it submits multiple comments.
But if you look at my code it says keyUp
not keyDown
! I'm pretty sure when you hold down a key down, it still only keyUp
once.
I've looked through stackoverflow, etc for about 2 hours now, hopefully this question will help my situation.