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

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

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

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

After i send get request

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

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

答案1

得分: 1

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

  1. <select name='ObjectGUID' class="form-select" id="select2">
  2. <option {% if savedValue == '' %}selected{% endif %}>请选择对象:</option>
  3. {% for obj in objects %}
  4. <option {% if savedValue == obj.GUID %}selected{% endif %} value="{{ obj.GUID }}">{{ obj }}</option>
  5. {% endfor %}
  6. </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:

  1. &lt;select name=&#39;ObjectGUID&#39; class=&quot;form-select&quot; id=&quot;select2&quot;&gt;
  2. &lt;option {% if savedValue == &#39;&#39; %}selected{% endif %}&gt;Выберите объект:&lt;/option&gt;
  3. {% for obj in objects %}
  4. &lt;option {% if savedValue == obj.GUID %}selected{% endif %} value=&quot;{{ obj.GUID }}&quot;&gt;{{ obj }}&lt;/option&gt;
  5. {% endfor %}
  6. &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:

确定