Reputation: 946
I'm attempting to pass a value on a hidden input field in a formset. However when I hit submit I get nothing back: 'form-0-my-field': ['']. Can anyone please help me with this issue?
Here's my form:
class MyForm(forms.Form):
my_field = forms.CharField(widget=forms.HiddenInput(attrs={
'class': 'my_field'}))
formset:
MyFormSet = formset_factory(MyForm, max_num=5)
views.py
def my_view(request):
if request.method == 'POST':
formset = MyFormSet(request.POST)
if formset.is_valid():
print(formset.cleaned_data)
else:
formset = MyFormSet()
return render(request, 'my_template.html', ctx={'formset': formset})
And finally my template with a script in the end to target my_field:
{% for form in formset.forms %}
{% for field in form.visible_fields %}
{# Include the hidden fields in the form #}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors.as_ul }}
{{ field }}
</td>
{% endfor %}
<button type="submit">Submit</button>
<script>
document.getElementsByClassName("my_field").value = "some str";
alert(document.getElementsByClassName("my_field").value);
</script>
Upvotes: 0
Views: 148
Reputation: 599788
Classes can match multiple elements. So document.getElementsByClassName
returns an HTMLCollection, ie an array of objects (note the s
in the method name).
To assign a value you need to reference the item within the collection:
document.getElementsByClassName("my_field")[0].value = "some str";
However preferably you would do this via IDs rather than classes.
Upvotes: 1