user1632928
user1632928

Reputation: 252

getting hidden Django field with JavaScript

In my form I have a hidden FloatField:

test         = forms.FloatField( widget=forms.HiddenInput())

Django generates the following html:

<input type="hidden" name="test_set-0-test" id="id_test_set-0-test" />

I want to silently fill this field with JavaScript:

document.getElementById('id_test_set-0-test').value = X

But I do not know if Django will always generate the same id "id_test_set-0-test"?

Is there a better way for finding in JavaScript Django element by id?

Or maybe its possible to enforce id in Django backend?

Thans!

Upvotes: 1

Views: 1719

Answers (3)

Nal
Nal

Reputation: 2771

You can manually set the ID attribute for the hidden field. docs

test = forms.FloatField( widget=forms.HiddenInput(attrs={'id':'some-custom-test-id'}))

Of course this only works when there is one instance of this form on the page. You could also manually set a class attribute through this method then select all the hidden fields and do with them as your please.

Upvotes: 1

Brandon Taylor
Brandon Taylor

Reputation: 34583

If this field is part of a form that's in a formset and you're using the standard Django way of rendering the formset, then yes, Django will automatically control the ID.

There are other ways to access this element other than id. You can select the element by css class, or by it's position in the DOM, a combination of those properties or other properties on the element like data-[your-property-here]

If the ID property is dynamic, in the case of a formset, I would select the element by it's position in the dom.

Upvotes: 0

user1614526
user1614526

Reputation: 474

Django always generate the same id don't worry about it

and i think this is only the better way i know only jquery i would love to get value like

 $('#id_test_set-0-test').val();

the way that you are doing is right

Upvotes: 0

Related Questions