我有三個具有相同選項的下拉串列,所有這些都是從資料庫中填充的并且作業正常。我想實作一個“智能映射”功能,其中三個欄位是根據條件預先選擇的。目前,預選的選項是下拉串列的第一個值(即Container ID)。我希望預先選擇的選項是特定值,而不是如附件影像中所示。
當前預選值:

所需的預選值

動態下拉串列選項

Python 代碼(燒瓶)
# db_col is the list of the three labels of the HTML form
db_col = ['Container ID', 'Container Type', 'Date of Manufacture']
# df_list is the list of the six options available in the dropdown list
df_list = ['Container ID', 'Container Type', 'Unit', 'Year of Manufacture', 'Date of Manufacture', 'Age']
# smart_mapping is the list of the three pre-selected options for the label in order
smart_mapping = ['Container ID', 'Container Type', 'Date of Manufacture']
# smart_mapping_dict is the dictionary of the labels as keys and pre-selected options as values
smart_mapping_dict = {'Container ID': 'Container ID', 'Container Type': 'Container Type', 'Date of Manufacture': 'Date of Manufacture'}
HTML 表單(Jinja 模板)
<form class="uploadDataForm" action="/mapping2/{{ id }}" method = "POST">
{% for fetchcol in db_col %}
<label for="{{ fetchcol }}">{{ fetchcol }}</label>
<select class="form-select" name="{{ fetchcol }}" id="fetchcol{{ loop.index }}" onclick="changeColumnCol{{ loop.index }}(this.value)" >
{% for ex_col in df_list %}
<option value="{{ ex_col }}">{{ ex_col }}</option>
{% endfor %}
</select>
<br>
{% endfor %}
<div class="text-center">
<a href="/second_page/{{ id }}" class="btn btn-danger">Discard Data Tape</a>
<button class="btn btn-default nextBtn text-center ">Next</button>
</div>
</form>
我試圖搜索類似的問題和答案,但它們需要使用 javascript 和/或 php 方法,這兩種方法我都不熟悉,因此無法適應我的問題。如何讓我的 HTML 表單預先選擇所需的選項,如圖 2 所示?
編輯:所需選項通常與標簽名稱不同,即“制造日期”標簽可能對應于“年齡”選項,而不是智能映射功能。
uj5u.com熱心網友回復:
您可以通過使用 Jinja 的if宣告來做到這一點。基本上,我們檢查當前選項是否等于smart_mapping_dict. 如果是這樣,我們將屬性添加selected到 HTML<option>標記以預先選擇它。
<form class="uploadDataForm" action="/mapping2/{{ id }}" method = "POST">
{% for fetchcol in db_col %}
<label for="{{ fetchcol }}">{{ fetchcol }}</label>
<select class="form-select" name="{{ fetchcol }}" id="fetchcol{{ loop.index }}" onclick="changeColumnCol{{ loop.index }}(this.value)" >
{% for ex_col in df_list %}
{% if ex_col == smart_mapping_dict[fetchcol] %}
<option value="{{ ex_col }}" selected>{{ ex_col }}</option>
{% else %}
<option value="{{ ex_col }}">{{ ex_col }}</option>
{% endif %}
{% endfor %}
</select>
<br>
{% endfor %}
<div class="text-center">
<a href="/second_page/{{ id }}" class="btn btn-danger">Discard Data Tape</a>
<button class="btn btn-default nextBtn text-center ">Next</button>
</div>
</form>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/472785.html
