ruggalainen ruggalainen - 21 days ago 4x
Javascript Question

Chained Dropdown in flask, get data from sqlite database

I am trying to get a html select tag with different counties (getting from database), when the user have selected a county, I want another select tag to enable and show the cities in that county (I have the data in a sqlite database, where the county id is in the city database). I am using python in Pycharm, with flask and I haven't found any good tutorials.

Is there an easy way of using some extension to flask? I saw something about sijax, but I never understood how to use it.

The code I have is something like this, but I guess the city-part has to be created through some javascript thingy:

<div class="form-group">
<label for="inputCounty">County</label>
<select class="form-control" id="select_county" name="select_county">
<option value="">Choose county</option>
{% for county in counties %}
<option value="{{ }}">{{ }}</option>
{% endfor %}
<div class="form-group">
<label for="inputCity">City</label>
<select class="form-control" id="select_city" name="select_city">
<option value="">Choose city</option>
{% for city in cities %}
<option value="{{ }}" class="{{ city.county }}">{{ }}</option>
{% endfor %}

I tried a "chained"-javascipt plugin but it didn't work, but that's why I have class in the option tags.

Right now the counties and all cities are sent to the html template, but I don't think that will be sustainable later on because I want to add another dropdown with places in the cities as well, so then I have to send a lot of data that never will be used.


In your head, add a handler for changing the values of the selects:

<script type="text/javascript">
    $("#select_county").change(function() {
            type: "POST",
            url: "{{ url_for('select_county') }}",
            data: {
                county: $("#select_county").val()
            success: function(data) {

This uses jquery.change to detect when the county select is changed and jquery.ajax to send that selected value to your backend, which would be something like:

@app.route('/select_county', methods=['POST'])
def select_county():
    ret = ''
    for entry in ...your_database_query...:
        ret += '<option value="{}">{}</option>'.format(entry)
    return ret

This list of <option> tags is then inserted into the second select through jquery.html.