【问题标题】:How to add all form's elements on submit in Meteor.js?如何在 Meteor.js 中提交时添加所有表单的元素?
【发布时间】:2018-03-19 05:37:17
【问题描述】:

我正在尝试创建一个在输入字段中输入信息后保存信息的应用程序!我在添加具有多个输入字段的表单时遇到了一些问题。

这些是我的 HTML 和 JS 文件:

import { Template } from 'meteor/templating';

import { Tasks } from '../api/tasks.js';

import './body.html';

Template.body.helpers({
  tasks() {
    // Show newest tasks at the top
    return Tasks.find({}, { sort: { createdAt: -1 } });
  },
});

Template.body.events({
  'submit .new-task'(event) {
    // Prevent default browser form submit
    event.preventDefault();

    // Get value from form element
    const target = event.target;
    const text = target.text.value;

    // Insert a task into the collection
    Tasks.insert({
      text,
      createdAt: new Date(), // current time
    });

  },
});
<body>
  <div class="container">
    <header>

      <form class="new-task">
        <input type="text" name="text" placeholder="Type to add new tasks" />
      </form>
    </header>

    <ul>
      {{#each tasks}}
        {{> task}}
      {{/each}}
    </ul>
  </div>
</body>

<template name="task">
  <li>{{text}}</li>
</template>

请告诉我如何添加超过 2 个输入,并通过单击提交按钮显示它?

【问题讨论】:

  • 很难理解您的问题是什么。但是您是否尝试重复 将 name="text" 替换为替代属性名称并相应地修改数据引用?

标签: javascript meteor meteor-blaze


【解决方案1】:

真的不清楚你的问题是什么。这可以像只包含第二个文本字段并将其与第一个字段同时保存到 mongo 一样简单吗?

html:

<form class="new-task">
  <input type="text" name="text" placeholder="Type to add new tasks" />
  <input type="text" name="text2" placeholder="Type to add something else" />
</form>

js:

const target = event.target;
const text = target.text.value;
const text2 = target.text2.value;

Tasks.insert({ text, text2, createdAt: new Date() });

【讨论】:

  • 您的代码不起作用(无法读取 Object.click .subm (body.js:20) -const text = target.text.value 处未定义的属性“值”;- 那条(
  • 对不起。这是我的错误。您的代码有效!谢谢)请更改您的答案-为此: const target = event.target;常量文本 = target.text.value;常量 text2 = target.text2.value; Tasks.insert({ text, text2, createdAt: new Date() }); target.text.value = ''; target.text2.value = '';
【解决方案2】:

我建议看看这个用于 Meteor 表单管理的超棒软件包:https://github.com/aldeed/meteor-autoform

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多