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

Node.js+Express-Handlebars下拉框提交后无法保留选中项问题

解决Express-Handlebars提交表单后下拉框保留选中值的问题

1. 后端传递选中值到视图

提交表单后,从请求体中获取用户选中的选项值,渲染视图时将该值和选项列表一起传入模板:

// 处理POST表单提交的路由
app.post('/filter', async (req, res) => {
  // 获取用户选中的下拉框值(假设下拉框name为category)
  const selectedCategory = String(req.body.category);
  // 从数据库查询所有下拉选项
  const categories = await Category.find();
  // 渲染视图时传入选中值和选项列表
  res.render('index', { categories, selectedCategory });
});

// GET请求初始化页面时,默认选中值可设为空或第一个选项
app.get('/', async (req, res) => {
  const categories = await Category.find();
  res.render('index', { categories, selectedCategory: categories[0]?._id || '' });
});

2. 配置Handlebars判断助手

注册自定义助手简化模板中的选中状态判断,避免重复代码:

const exphbs = require('express-handlebars');

const hbs = exphbs.create({
  helpers: {
    // 判断当前选项是否为选中项
    isSelected: function(currentVal, selectedVal) {
      return currentVal === selectedVal ? 'selected' : '';
    },
    // 可选:注册相等判断助手,用于模板直接写条件
    eq: function(a, b) {
      return a === b;
    }
  }
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

3. 修改前端Handlebars模板

在下拉框的<option>标签中使用助手标记选中状态:

<form method="POST" action="/filter">
  <select name="category">
    {{#each categories}}
      <!-- 使用自定义isSelected助手 -->
      <option value="{{this._id}}" {{isSelected this._id ../selectedCategory}}>{{this.name}}</option>
      
      <!-- 或者直接用eq助手写条件 -->
      <!-- <option value="{{this._id}}" {{#if (eq this._id ../selectedCategory)}}selected{{/if}}>{{this.name}}</option> -->
    {{/each}}
  </select>
  <button type="submit">提交</button>
</form>

关键注意事项

  • 确保selectedCategory和选项value的类型一致:如果数据库返回的是ObjectId,需转成字符串(如String(req.body.category)),避免类型不匹配导致判断失效。
  • 如果是GET请求提交表单,需从req.query而非req.body中获取选中值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 01:20:02