我有以下带有提交按钮的选择。我非常希望所选选项重定向到我的路线,而无需我按下提交按钮,这样我就可以摆脱它了。
<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);
如果我正确理解了你的问题,你想要:
"some/route"
如果是这样,那么这可能会有所帮助:
function checkSelected() { if (this.value === "some/route") return (window.location = this.value); if (this.value) this.form.submit(); } const EL_select = document.querySelector("#filter_query"); if (EL_select) EL_select.addEventListener("change", checkSelected); <form> <select class="form-control" id="filter_query" name="filter_query"> <option selected value="">Please select a type</option> <option value="aaa">aaa</option> <option value="bbb">bbb</option> <option value="etc">etc</option> <option value="xxx">Create new type...</option> </select> </form>
附言:
onchange="checkSelected()"