Guillermo Brachetta
Guillermo Brachetta

Reputation: 4775

Trigger redirect on option selected

I have the following select tag with options populated from a Mongo database, and would like to have the latest option tag to redirect me to my template to create new options.

<select class="custom-select" id="perfume_type" name="perfume_type">
    <option disabled selected>Choose type</option>
    {% for type in types %}
        <option value="{{ type.type_name }}">{{ type.type_name }}</option>
    {% endfor %}
    <option value="{{ url_for('new_type') }}">Create new type...</option>
</select>

What would be the best approach to trigger automatically that redirect when the last option (outside the loop) is selected?

Upvotes: 0

Views: 106

Answers (1)

ngShravil.py
ngShravil.py

Reputation: 5058

You can achieve it with simple Javascript and HTML. You need to do the following changes:

  1. Add an onchange even on the select tag.
<select class="custom-select" id="perfume_type" name="perfume_type" onchange="checkSelected()">
  1. Add the JavaScript method, which will check whether it's the last selected option or not. If it's the last selected option, then redirect.
<script>
    function checkSelected() {
        var selected = document.getElementById('perfume_type');
        var option = selected.options[selected.options.length-1];
        if (option.selected == true) {
            window.location = option.value;
        }
    }
</script>

I hope the above works.

Upvotes: 1

Related Questions