如何获取jQuery动态生成的select选项值并传递接收至Node.js后端
编辑:问题已解决
问题为个人操作失误,评论区指出问题出在如下去重代码部分:
//The area where I deal with duplicates $("#grupoSelected option").val(...)
问题根源是*.val()方法*使用错误,将去重逻辑替换为以下代码即可解决:
let map = {}; $("select option").each(function () { if(map[this.value]) { $(this).remove(); } map[this.value] = true; });
原问题描述
我尝试了所有能找到的解决方案均无效果,暂时无法定位出错点,本人对相关技术栈熟练度有限。我想要实现的需求是:获取grupoSelected和hospitalSelected两个下拉框中由jQuery动态生成的option的值,提交后可在Node.js后端正常接收。
我定义了如下两个select下拉框:
<select name="grupoSelected" id="grupoSelected" class="select form-control floating" required> <option value=""> -- selecione um grupo -- </option> </select> <select name="hospitalSelected" id="hospitalSelected" class="select form-control floating" required> <option hidden disabled selected value> -- selecione um hospital -- </option> </select>
两个下拉框的option通过ajax请求结合jQuery动态填充,具体代码如下:
群组下拉框(选项由上一级下拉框选中的班级决定)
$("#turmaSelected").on('change', function () { let turmaSelected = $(this).val(); $.ajax({ url: '/info/turma', type: 'POST', data: { turma: turmaSelected }, success: function (data) { let grupo = jQuery.parseJSON(data); $(grupo).each((i, e) => { $('#grupoSelected').append(`<option value="${e.id}"> ${e.nome_grupo} </option>`) //$('<option>').attr(e.id).text(e.nome_grupo).appendTo('#grupoSelected'); }); // 去重逻辑:不同班级可能存在同名群组 $("#grupoSelected option").val(function (id, val) { $(this).siblings('[value="' + val + '"]').remove(); }); }, error: function (error) { if (error.message === undefined || error === "") { $("#error_alert").show(); $('#error_alert').text('Nenhum grupo foi encontrado.'); } console.log('Error: ' + error.message); } }); });
医院下拉框填充代码
$.ajax({ url: '/info/hospital', type: 'GET', success: function (result) { let hospital = jQuery.parseJSON(result); $(hospital).each((i, e) => { $("#hospitalSelected").append(`<option value='${hospital[i].nome_hospital}'>${hospital[i].nome_hospital}</option>`); }); $("#hospitalSelected option").val(function (idx, val) { $(this).siblings('[value="' + val + '"]').remove(); }); }, error: function (error) { if (error.message === undefined || error === "") { $("#error_alert").show(); $('#error_alert').text('Nenhum hospital foi encontrado.'); } console.log('Error: ' + error.message); } });
目前的问题是:即使在HTML结构中也没有正常给option赋值,提交表单后Node.js后端接收到的参数如下,grupoSelected和hospitalSelected两个字段值为空:
{ turmaSelected: 'md9', grupoSelected: '', discSelected: 'clinicaMedica', hospitalSelected: '', rodizio_numero: '1', data_inicio: '07/09/2021', data_fim: '07/09/2021' }
使用的技术栈为:express、ejs、sequelize、Node.js、postgresql、bootstrap 4(因所用模板内置该版本,升级成本较高暂未更新)。
控制器相关代码如下:
const { turmaSelected, grupoSelected, discSelected, hospitalSelected, rodizio_numero, data_inicio, data_fim, } = req.body;
app.js核心配置代码如下:
app.use(cookieParser()); app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.use(bodyParser.text({ extended: true }));
恳请各位提供解决方案,谢谢。
内容的提问来源于stack exchange,提问作者Wesley G P Gomes
相关产品推荐
相关产品推荐

