如何使用表单一次提交多个数据

时间:2016-06-21 06:21:01

标签: node.js forms mongodb express

这个问题措辞笨拙,所以请耐心解释。

我正在使用Node.js,Express和MongoDB。

以下是表单提交的后端代码:

router.post('/inputlog', function(req, res) {
Log.findOne({logTitle: req.body.logTitle}, function(err, existingLog) {
    if(!existingLog) {
        req.flash('errors', req.body.logTitle + ' was not found');
        return res.redirect('/inputlog');
    }
    if(existingLog) {
        Lot.findOneAndUpdate({logTitle: req.body.logTitle}, {
            $push: {
                OutdoorLogs: {
                    LogInput: {
                        logDate: req.body.logDate,
                        logInput: req.body.logInput
                    }
                }
            }
        }, {safe: true, upsert: false}, function (err, logSuccess) {
            if(err) {
                req.flash('errors', 'Log was not inserted due to Error.');
                return res.redirect('/inputlog');
            }
            if(logSuccess) {
                req.flash('success', req.body.logTitle+ ' Log has been updated. ');
                return res.redirect('/inputLog');
            }
        });
    }
})
});

所有这一切是什么意思?基本上,我有一个输入日志的表单。您首先为日志添加标题。然后,它将在数据库(MongoDB)中搜索您输入的日志的标题。如果不存在此类日志标题,则会向用户发送错误。

如果日志标题确实存在,它会将“logDate”和“logInput”添加到该日志标题的数组中。

这一切都很好。但!如果我想在相同的时间输入多个日志(多个logDate和logInput),该怎么办?我设置表单的方式,我只能一次一个地输入一个新的日志,这里是我的表格供参考:

<form method="POST" action="/inputlog">
    <div class='form-group'>
        <label for="logTitle">Log Title</label>
        <input type="text" name="logTitle" autofocus class="form-control uppercase" id="logTitle"/>
    </div>
    <div class='form-group'>
        <label for="logDate">Log Date</label>
        <input type="text" name="logDate" class="form-control logDate" id="logDate"/>
    </div>
    <div class='form-group'>
        <label for="logInput">log Input</label>
        <input type="text" name="logInput" class="form-control logInput" id="logInput"/>
     </div>
     <div class='form-group'>
         <input type="submit" class="btn btn-default btn-primary pull-right" value="submit">
   </form>

所以,再次,这个表单的设置方式,我一次只能输入一个 log 。如果我想一次输入20个不同的日志,我将不得不一次一个地输入(输入日志,点击提交,输入日志,点击提交等等)。

如何只用一次提交输入多个日志(条目)?

1 个答案:

答案 0 :(得分:0)

为什么不重构表单,以便一旦完成一个条目,就会出现一组额外的输入。我会在每个输入上使用onblur检查表单以确保每个输入都有一些文本,如果它确实运行了一个函数来添加一个额外的表单。为每个可以对应数组索引的表单组创建一个id,并使用字段推送一个对象。这样,如果稍后编辑它们,可以在提交之前修改它们。

相关问题