New approach: Event Delegation

This works as follows:

The div where the input fields for the subjects live got an id. The script now listens to all keypresses in this div, but only does something if it is within an INPUT field. If it is an INPUT field within this div, it looks for keyCode 13. If it is 13, preventDefault() is triggered.  Else nothing happens.
This commit is contained in:
Jascha Urbach 2022-12-20 11:36:14 +01:00
parent 259ceeea21
commit 105144a026
No known key found for this signature in database
GPG key ID: A43A844B114F9B08
2 changed files with 9 additions and 5 deletions

View file

@ -47,11 +47,15 @@
.querySelectorAll("[data-remove]") .querySelectorAll("[data-remove]")
.forEach((node) => node.addEventListener("click", removeInput)); .forEach((node) => node.addEventListener("click", removeInput));
document.querySelectorAll("[name='subjects']").forEach((node) => // Get the element, add a keypress listener...
node.addEventListener("keypress", function (event) { document.getElementById("subjects").addEventListener("keypress", function (e) {
// e.target is the element where it listens!
// if e.target is input field within the "subjects" div, do stuff
if (e.target && e.target.nodeName == "INPUT") {
// Item found, prevent default
if (event.keyCode == 13) { if (event.keyCode == 13) {
event.preventDefault(); event.preventDefault();
} }
}) }
); });
})(); })();

View file

@ -81,7 +81,7 @@
{% include 'snippets/form_errors.html' with errors_list=form.languages.errors id="desc_languages" %} {% include 'snippets/form_errors.html' with errors_list=form.languages.errors id="desc_languages" %}
</div> </div>
<div class="field"> <div class="field" id="subjects">
<label class="label" for="id_add_subjects"> <label class="label" for="id_add_subjects">
{% trans "Subjects:" %} {% trans "Subjects:" %}
</label> </label>