'Django form submit through Javascript returns empty fields
I have a form in my HTML document for which I suggest a few examples on how to fill it. The user can click on one of these examples and it will call a javascript function that pre-fill and submits the form.
The submit function works correctly but it returns empty fields. Do you have any idea why?
My HTML: form has 5 fields (amount, category, title, expiration, priority), 4 examples:
<form method="POST" id="myform">
{% csrf_token %}
<label for="amount" class="form-label h6 mb-0 text-dark font-weight-bold" style="width: 120px;">Target amount</label>
<input name="amount" id="amount" placeholder="0" style="width: 200px;">
<input type="hidden" name="category" id="category">
<input type="hidden" name="title" id="title" value="">
<input type="hidden" name="expiration" id="expiration">
<input type="hidden" name="priority" id="priority">
<div class="goals-template align-items-center text-center mb-4">
<a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_emergency2.svg' %}">Emergency Fund</a>
<a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_car2.svg' %}">New car</a>
<a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_house2.svg' %}">House</a>
<a class="template" onclick="FormSubmit(this)"><img class="template-item" src="{% static 'img/undraw_wishlist2.svg' %}">Wishlist</a>
<button type="submit" class="d-none" id="Go">Save goal</button>
</div>
</form>
My JS:
function FormSubmit(e) {
var myform = document.getElementById("myform");
document.getElementById('category').value = 'RETIREMENT';
document.getElementById('title').value = '10';
document.getElementById('amount').value = 10;
document.getElementById('expiration').value = '2022-12-31';
document.getElementById('priority').value = 'NEED';
getCookie('csrftoken');
var hiddenField1 = document.createElement("input");
hiddenField1.setAttribute("type", "hidden");
hiddenField1.setAttribute("name", 'csrfmiddlewaretoken');
hiddenField1.setAttribute("value", getCookie('csrftoken'));
myform.appendChild(hiddenField1);
myform.submit();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|

