Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass parameters on onChange of html select with flask-wtf

The following flask code creates a select .. option dropdown menu:

model:

class SelectForm(Form):
    country = SelectField('Country', choices=[
        ('us','USA'),('gb','Great Britain'),('ru','Russia')])

flask app:

@app.route('/new')
def new():
    form = SelectForm()
    return render_template('new.html', form = form )

html file:

<form method=post action="/register">
    {{ render_field(form.country) }}
  <p><input type=submit value=Register>
</form>

macro file the defines render_field:

{% macro render_field(field) %}
  <dt>{{ field.label }}
  <dd>{{ field(**kwargs)|safe }}
  {% if field.errors %}
    <ul class=errors>
    {% for error in field.errors %}
      <li>{{ error }}</li>
    {% endfor %}
    </ul>
  {% endif %}
  </dd>
{% endmacro %}

What is the best way to have onchange submit the results automatically without the user having to press the submit button? Is there a way to change the macro or what's the most elegant way?

thanks

like image 872
Nickpick Avatar asked Jun 23 '16 23:06

Nickpick


People also ask

How do you create a dynamic form in flask?

you have to create a dynamic form at view function, fetch the form field you want to get, and iterate every field to construct this form object. I used for fieldtypes simple text instead of integer values. Since it seems easy to read at code level.

What is FlaskForm?

FlaskForm Class. Flask provides an alternative to web forms by creating a form class in the application, implementing the fields in the template and handling the data back in the application. A Flask form class inherits from the class FlaskForm and includes attributes for every field: class MyForm(FlaskForm):

How does Onchange event work in JavaScript?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.


1 Answers

It can be done by add javascript onchange function as attribute

<form method=post action="/register">
    {{ render_field(form.country(**{"onchange":"this.form.submit()"})) }}
  <input type=submit value=Register>
</form>
like image 160
Suraj Avatar answered Oct 06 '22 16:10

Suraj