Abstract JS for multivalue form fields

This commit is contained in:
Chad Nelson 2021-11-21 17:18:18 -05:00
parent 8a6f78cfff
commit 6be9ac4f70
3 changed files with 29 additions and 5 deletions

View file

@ -368,4 +368,22 @@ let BookWyrm = new class {
); );
} }
} }
duplicateInput (input_id ) {
const orig = document.getElementById(input_id);
const parent = orig.parentNode;
const new_count = parent.querySelectorAll("input").length + 1
let input = orig.cloneNode();
input.id += ("-" + (new_count))
input.value = ""
let label = parent.querySelector("label").cloneNode();
label.setAttribute("for", input.id)
parent.appendChild(label)
parent.appendChild(input)
}
}(); }();

View file

@ -119,10 +119,16 @@
</fieldset> </fieldset>
{% endif %} {% endif %}
<div class="field"> <div class="field">
<label class="label" for="id_add_author">{% trans "Add Authors:" %}</label> <label class="label">{% trans "Add Authors:" %}</label>
<input class="input" type="text" name="add_author" id="id_add_author" placeholder="{% trans 'John Doe, Jane Smith' %}" value="{{ add_author }}" {% if confirm_mode %}readonly{% endif %}> {% for author in add_author %}
<span class="help">{% trans "Separate multiple values with commas." %}</span> <label class="label is-sr-only" for="id_add_author{% if not forloop.first %}-{{forloop.counter}}{% endif %}">{% trans "Add Author" %}</label>
<input class="input" type="text" name="add_author" id="id_add_author{% if not forloop.first %}-{{forloop.counter}}{% endif %}" placeholder="{% trans 'Jane Doe' %}" value="{{ author }}" {% if confirm_mode %}readonly{% endif %}>
{% empty %}
<label class="label is-sr-only" for="id_add_author">{% trans "Add Author" %}</label>
<input class="input" type="text" name="add_author" id="id_add_author" placeholder="{% trans 'Jane Doe' %}" value="{{ author }}" {% if confirm_mode %}readonly{% endif %}>
{% endfor %}
</div> </div>
<span class="help"><a id="another_author_field" onclick="BookWyrm.duplicateInput('id_add_author')">{% trans "Add Another Author" %}</a></span>
</div> </div>
</section> </section>
</div> </div>

View file

@ -43,12 +43,12 @@ class EditBook(View):
if not form.is_valid(): if not form.is_valid():
return TemplateResponse(request, "book/edit/edit_book.html", data) return TemplateResponse(request, "book/edit/edit_book.html", data)
add_author = request.POST.get("add_author") add_author = request.POST.getlist("add_author")
# we're adding an author through a free text field # we're adding an author through a free text field
if add_author: if add_author:
data["add_author"] = add_author data["add_author"] = add_author
data["author_matches"] = [] data["author_matches"] = []
for author in add_author.split(","): for author in add_author:
if not author: if not author:
continue continue
# check for existing authors # check for existing authors