How to pre select multiple options using jinja2 and select2?

3k views Asked by At

I am trying to reatain data from my db and pre-select a multi select using select2 and jinja2.

My jija2/html code:

<span class="input-group-addon">Relocate Where</span>
        {% if not context.relocate_to %}
            <input class="form-control" id="relocate_to" value="" type="hidden" name="relocate_to" data-placeholder="Choose province" />
        {% else %}
            {% for v in context.relocate_to|batch(9, '&nbsp;') %}
                <input class="form-control" id="relocate_to" value="{{v}} " type="hidden" name="relocate_to" data-placeholder="Choose province" />
            {% endfor %}
        {% endif %}

my Js:

$.getJSON("{{'provinces.json'|route_url}}").success(function(data) {
        $("#relocate_to").select2({
            data:data,
            multiple: true
        maximumSelectionSize: 9
        });
    });

This only fills the multi select with 1 tag, this is wrong as there is 2 Provinces in the database for this user, and there can be 9 Provinces selected.

I have looked at these question, but it doesn't help me much.

How can I achieve my goal of retaining the data with jinja2 and select2?

Would it be better retaining the data using jQuery?

2

There are 2 answers

0
Renier On BEST ANSWER

I found an alternative way of doing what I wanted to do:

In my python code I create a dict with the data to create the select then I do this:

<span class="input-group-addon">relocate to</span>
    <select name="relocate_to" id="relocate_to" multiple="" class="form-control">
        {% for k, v in relocate_list.iteritems() %} <!-- relocate_list was a list, is now a dictionary -->
            {% if k in context.relocate_to %}
                <option value="{{ k }}" selected="">{{ v }}</option> 
            {% else %}
                <option value="{{ k }}">{{ v }}</option>
            {% endif %}
        {% endfor %}
    </select>

I hope this can help someone in the future.

Then I just initialize select2:

$("#relocate_to").select2({
        maximumSelectionSize : 9
    });
1
Andrew Kloos On

I wonder if it's because you have multiple elements with the same id... try this:

<input class="form-control" id="relocate_to_{{ loop.index }}" value="{{v}} " type="hidden" name="relocate_to" data-placeholder="Choose province" />

You will also need to getElementsByName for your js...

$.getJSON("{{'provinces.json'|route_url}}").success(function(data) {
        $("[name=relocate_to]").select2({
            data:data,
            multiple: true
        maximumSelectionSize: 9
        });
    });

Hope this helps.