You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask项目中如何将Python变量值传递至HTML的select与textarea标签

解决Flask中select和textarea表单回显数据的问题

嘿,我来帮你搞定这个表单回显的问题!你碰到的是HTML表单元素的一个常见特性——select和textarea的取值方式和普通input文本框不一样,咱们一步步来修正:

1. 修复textarea的回显问题

textarea标签不支持value属性,它的内容是直接写在标签内部的。你原来的代码用了value="{{address}}",这是无效的,改成把变量放在标签中间就行:

<label><b>Address</b></label>
<textarea class="textarea1" id="Address" name="Address" rows="4" cols="25">{{address}}</textarea><br/><br/>

这样当Flask渲染模板时,address的值就会直接填充到文本区域里了。

2. 修复select的回显问题

select需要给匹配的<option>标签添加selected属性来默认选中对应选项。你可以用Jinja2的条件判断,对比后端传过来的rtype值和每个option的value,相等的话就加上selected:

<label><b>Type of bed</b></label>
<select class="selector1" name="BType" id="BType">
  <option disabled {% if not rtype %}selected{% endif %} value=""> Select</option>
  <option value="General" {% if rtype == 'General' %}selected{% endif %}>General Ward</option>
  <option value="Shared" {% if rtype == 'Shared' %}selected{% endif %}>Semi Sharing</option>
  <option value="Single" {% if rtype == 'Single' %}selected{% endif %}>Single Room</option>
</select><br/><br/>

这里的{% if rtype == 'General' %}selected{% endif %}就是关键逻辑:当后端传来的rtype等于该option的value时,自动添加selected属性,实现默认选中。

3. 修正Python代码里的小bug

另外注意你的Python代码里有个笔误:

status=[9]

这行应该是status=i[9](你是想取数据库行的第10个字段对吧?),不然status会变成一个包含数字9的列表,后续如果用到这个变量也会出问题。

这样修改之后,你的select和textarea就能正常回显从数据库获取到的患者数据啦!

内容的提问来源于stack exchange,提问作者manthena anusha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:12:36