django-project/recipes/templates/recipe-form.html

60 lines
2.2 KiB
HTML

{% extends "base_main.html" %}
{% comment %}
Barn Web App - A collection of web-apps for my family's personal use,
including a recipe database.
Copyright © 2023 Benjamin Stadlbauer
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
General Public License for more details.
This program comes with a copy of the GNU Affero General Public License
file at the root of this project.
{% endcomment %}
{% block title %}{{ title }}{% endblock %}
{% block main %}
<form action="" method="post" id="version-form" enctype="multipart/form-data">
{%csrf_token %}
{% if recipe_form %}
{{ recipe_form.as_div }}
{% endif %}
{{ version_form.as_div }}
{{ ingredients_formset.management_form }}
{% for ingredient_form in ingredients_formset %}
{{ ingredient_form.as_div }}
{% endfor %}
<button id="add-ingredient" type="button">Add Ingredient</button>
<input type="submit" value="Submit">
</form>
<script>
let firstIngredientDiv = document.querySelector("input[id^=id_ingredient][id$=text]").parentElement;
let addIngredientButton = document.querySelector("#add-ingredient");
let form = document.querySelector("#version-form");
let totalIngredientFormsInput = document.querySelector("#id_ingredient-TOTAL_FORMS");
addIngredientButton.addEventListener('click', addIngredient);
function addIngredient(e) {
let nextIngredientIndex = document.querySelectorAll("input[id^=id_ingredient][id$=text]").length
e.preventDefault();
let newIngredientDiv = firstIngredientDiv.cloneNode(true);
let formRegex = new RegExp('ingredient-(\\d){1}-', 'g');
newIngredientDiv.innerHTML = newIngredientDiv.innerHTML.replace(formRegex, `ingredient-${nextIngredientIndex}-`);
form.insertBefore(newIngredientDiv, addIngredientButton);
totalIngredientFormsInput.setAttribute('value', `${nextIngredientIndex + 1}`);
}
</script>
{% endblock %}