我正在使用 npm formidable ( https://www.npmjs.com/package/formidable ) 来处理我的 Express js 应用程序中的表单。
我有这个表格:
<form action="/getchecks" method="post" enctype="multipart/form-data" id="set-featured-form">
<fieldset>
<input type="checkbox" name="featured" value="1">News 1 heading <br>
<input type="checkbox" name="featured" value="2">News 2 heading <br>
<input type="checkbox" name="featured" value="4">News 4 heading <br>
<input type="checkbox" name="featured" value="5">News 5 <br>
<input type="checkbox" name="featured" value="6">news 6 <br>
<input type="checkbox" name="featured" value="7">news 7 <br>
<input type="button" value="Save" id="save-featured">
</fieldset>
</form>
我希望用户能够选择多个复选框,然后在提交时我想知道选中了哪些复选框。但是,在这种情况下,它只返回最后选中的复选框。例如:如果我检查 1、5 和 7,它只会返回 7。这是我的路由器代码:
router.post('/getchecks', function (req, res, next){
getCheckboxes(req, res);
});
function getCheckboxes(req, res){
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files){
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write('received the data:\n\n');
res.end(util.inspect({
fields: fields
}));
});
}
这是输出:
received the data:
{ fields: { featured: '7' } }
如何让它向我传递已选中复选框的值数组?
谢谢。
最佳答案
您是否尝试过在精选末尾添加 [] ?
<form action="/getchecks" method="post" enctype="multipart/form-data" id="set-featured-form">
<fieldset>
<input type="checkbox" name="featured[]" value="1">News 1 heading <br>
<input type="checkbox" name="featured[]" value="2">News 2 heading <br>
<input type="checkbox" name="featured[]" value="4">News 4 heading <br>
<input type="checkbox" name="featured[]" value="5">News 5 <br>
<input type="checkbox" name="featured[]" value="6">news 6 <br>
<input type="checkbox" name="featured[]" value="7">news 7 <br>
<input type="button" value="Save" id="save-featured">
</fieldset>
</form>
更新
看起来这个问题已经被修复:#380
但是,这个 PR 还没有合并到 master 分支!
我进行了本地更改,它确实有效。
关于node.js - npm 强大的形式仅返回最后一个复选框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193880/