Karim N Gorjux
Karim N Gorjux

Reputation: 3033

jQuery hide and Django form widget

I'm using some jQuery code to hide and show a select in a form base on some circumstances. Everything it's fine, but I would like start the widget as hidden when the form is loaded the first time.

The jQuery hide/show manipulate the style of the select. When is hidden: display: hidden; when is shown: display: block;.

Is there a way to change the attr on the Django widget to add the style="display: hidden;"?

In the init of my form:

self.fields['state'].widget.attrs.update({..})

Is possible to set the style using the attr?

Upvotes: 1

Views: 411

Answers (1)

delinear
delinear

Reputation: 2805

I know you can do it with classes, I believe the syntax is like this:

self.fields['state'].widget.attrs.update({'class': 'hide'});

I'm assuming it would work with the style attribute too, if it does it should be something like this, but I'm not able to test it right now:

self.fields['state'].widget.attrs.update({'style': 'display:none'});

The class route is probably better anyway, you'd just need to create a .hide { display: none; } class in your CSS.

Upvotes: 2

Related Questions