开发者

How do I reveal an optional field in a Django form, when a checkbox is checked?

开发者 https://www.devze.com 2023-02-19 09:38 出处:网络
Is this possible with Django, withou开发者_如何转开发t using Javascript?It is technically possible using some CSS3 techniques, although there won\'t be universal browser support.

Is this possible with Django, withou开发者_如何转开发t using Javascript?


It is technically possible using some CSS3 techniques, although there won't be universal browser support.

Your field will have an id depending upon the form's prefix ('id' by default, configurable when creating a form), so you can style a form element in css with the identifier #id_field_name. Then you can use some CSS3 Selectors to get to your fields, something like this:

#id_checkbox_field ~ #id_hidden_field {display: none; }
#id_checkbox_field[checked] ~ #id_hidden_field { display: block; }

Of course, your selector will vary depending upon your document structure. The tilda will only work if id_checkbox_field and id_hidden_field share a parent, but you can theoretically set up your document structure so that this can be done with CSS3. If you want smooth animations, it's technically possible, but not easy and not well supported.

The alternative, as pjmorse said, is to have them check the box, submit the form, and have it come back with the new field displayed. Let me know if you want help figuring that out, it's a whole nother can of worms, and I doubt it's what you're looking for.

Most of the time, when you want to do something dynamically, you want to use javascript.


You mean reveal an optional field when the checkbox is checked? That's close to impossible in any framework without Javascript. Your simple options are either to use JS to reveal the optional field depending on the state of the checkbox, or make the checkbox actually post back to reload a different version of the form showing the optional field (and making the checkbox behave that way would require JS).

I imagine it might be possible to wrangle something together with CSS, but JS would actually be more reliable - and you might still need it to change the selectors of a container view.

0

精彩评论

暂无评论...
验证码 换一张
取 消