Lâm Huynh Van
Lâm Huynh Van

Reputation: 3

How to render a field when radio button is checked?

I use WTForms and have a radio field like that:

class SimpleForm(Form):
     radio_choice = RadioField('Label', choices=[('ip', 'IP'), ('ifname','Ifname')], default = 'ip')

In my html, I use jinja2 syntax:

 {{ render_field(form.radio_choice) }}
 {{ form.radio_choice.data }}
 {% if form.radio_choice.data == ip %}
      {{ render_field(form.weight) }}
 {% else %}
      {{ render_field(form.domain) }}
 {% endif %}

How can I can get form.radio_choice.data on html, I wanna render domain field when form.radio_choice.data == ifname but I can only catch the value like that:

@app.route('/',methods=['post','get'])
def hello_world():
    form = SimpleForm()
    if form.validate_on_submit():
        print form.radio_choice.data

Upvotes: 0

Views: 919

Answers (1)

Titotix
Titotix

Reputation: 55

It looks like you misunderstood what does jinja templating. Jinja is interpreted on the server side, when you execute render_template() After that, it's sent to the client and the client can fill up your form. So when your jinja template is interpreted, there is yet no data in your fields.

For your purpose, you will need to write some javascript code which executes on the client side, when the client is filling up the form. At this time, javascript can have the data and then display whatever you wish according to the choice on the radio button.

You can start by getting the radio button value : How to get the selected radio button’s value?

Upvotes: 1

Related Questions