【发布时间】:2020-05-23 16:00:30
【问题描述】:
我有以下带有提交按钮的选择。 我真的很想选择重定向到我的路线的选项,而我不需要按下提交按钮,所以我可以摆脱它。
<form action="{{ url_for("perfumes.filters") }}" class="search-form">
<div class="form-group">
<label for="exampleFormControlSelect1">Filter by Type</label>
<select class="form-control" id="filter_query" name="filter_query" onchange="checkSelected()">
<option selected='true' name="" value="" id="">Please select a type</option>
{% for type in types %}
<option value="{{type['type_name']}}" id="{{type['type_name']}}" name="{{type['type_name']}}">{{type['type_name']}}</option>
{% endfor %}
<option value="{{ url_for('types.new_type') }}">Create new type...</option>
</select><br>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>
</div>
</form>
最后一个选项(创建新类型)已经使用此函数重定向到其对应的路由。
function checkSelected() {
const selected = document.getElementById("filter_query");
const option = selected.options[selected.options.length - 1];
if (option.selected == true) {
window.location = option.value;
}
}
调整该功能的最佳方法是什么,以便我可以取消“提交”按钮并在选择时自动触发重定向?
更新:
这一切都在运行良好,但是当循环外选项被选中
时,我会得到一个控制台错误<form id="form" action="{{ url_for("perfumes.filters") }}" class="search-form">
<div class="form-group">
<label for="exampleFormControlSelect1">Filter by Type</label>
<select class="form-control" id="filter_query" name="filter_query">
<option selected='true' name="" value="" id="">Please select a type</option>
{% for type in types %}
<option value="{{ url_for('perfumes.filters', filter_query=type['type_name']) }}">{{type['type_name']}}</option>
{% endfor %}
<option value="{{ url_for('types.new_type') }}">Create new type...</option>
</select><br>
<button class="btn btn-primary btn-sm" type="submit">Submit</button>
</div>
</form>
还有脚本:
function checkSelected() {
if (this.value) window.location = this.value;
}
const EL_select = document.querySelector("#filter_query");
EL_select.addEventListener("change", checkSelected);
【问题讨论】:
-
您在寻找
$router.push吗?你可以把它放到checkSelected -
您希望它重定向到哪个 URL?
标签: javascript python flask