如何在提交表单后保存选择的选项在选择框中。

huangapple go评论86阅读模式
英文:

how to save selected option in select after send form

问题

我在表单中选择了一个选项,并将该值发送到我的后端。我想知道是否有办法保存我发送的值在我的选择框中,以免它切换到默认选项。

英文:

I have select in form and i send value from option to my backend

I was wondering if there's way to save value that i've send in my select

template.html


<form method="get" class="mb-3">
    <div class="row">
        <div class="col-8 w-25 custom-select">
            <form method="get" class="w-50 custom-select">
                <select name='ObjectGUID' class="form-select" id="select2">
                    <option value="" disabled selected>Выберите объект:</option>
                    {% for obj in objects %}
                        <option value="{{ obj.GUID }}">{{ obj }}</option>
                    {% endfor %}
                    <option value="1">1</option>
                    <option value="2">2</option>
                </select>
                <button type="submit" class="mb-3 ms-2 mt-3 btn btn-outline-primary w-50">Применить</button>
            </form>
        </div>
    </div>
</form>

After i send get request

如何在提交表单后保存选择的选项在选择框中。

But i want select not to switch to default option
如何在提交表单后保存选择的选项在选择框中。

答案1

得分: 1

你需要验证是否已经为此字段保存了一个值,然后可以在选择的选项上设置一个selected属性。例如:

<select name='ObjectGUID' class="form-select" id="select2">
  <option {% if savedValue == '' %}selected{% endif %}>请选择对象:</option>
  {% for obj in objects %}
    <option {% if savedValue == obj.GUID %}selected{% endif %} value="{{ obj.GUID }}">{{ obj }}</option>
  {% endfor %}
</select>

这里的 savedValue 是您在提交表单上保存的变量。

英文:

You need verify if there's already a value saved for this field, then you can set a selected attribute on your select's option. For exemple:

  &lt;select name=&#39;ObjectGUID&#39; class=&quot;form-select&quot; id=&quot;select2&quot;&gt;
    &lt;option {% if savedValue == &#39;&#39; %}selected{% endif %}&gt;Выберите объект:&lt;/option&gt;
    {% for obj in objects %}
      &lt;option {% if savedValue == obj.GUID %}selected{% endif %} value=&quot;{{ obj.GUID }}&quot;&gt;{{ obj }}&lt;/option&gt;
    {% endfor %}
  &lt;/select&gt;

This savedValue is the var you have saved on your submit form.

huangapple
  • 本文由 发表于 2023年4月17日 22:12:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036101.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定