forms - Meteor:如何在一组表单字段中接受用户输入

标签 forms meteor

Meteor 的新功能。我有一个包含多个字段的表单

<template name="addcityform">
  <form name="addcity">
    <input name="city" class="city" type="text">
    <input name="population" class="population" type="text">
    <input type="Submit" value="Add City">
  </form>
</template>

我只是想将字段插入到数据库中,但我不知道该怎么做。经过几次尝试,这是我目前拥有的:

Template.addcityform.events({
  'submit .addcity' : function(evt, template) {
    Cities.insert({
      city: template.find('input.city').value,
      population: template.find('input.population').value
    });
  }
});

// this gives: Uncaught TypeError: Cannot read property 'value' of null 

我看到了一些使用 Session.setdocument.getElementById 的示例,但由于可能存在命名空间冲突,这对我来说似乎很笨拙。我想以“正确的方式”这样做,以便以后可以扩展,例如,我可以将表单的多个实例放到页面上,它们应该相互独立。执行此操作的“正确方法”是什么?

最佳答案

“提交表单”处理程序中缺少 event.preventDefault(),否则页面将重新加载并破坏 Meteor 的单页应用程序体验。

我会做类似的事情:

<template name="addcityform">
    <form>
        <input name="city" class="city" type="text">
        <input name="population" class="population" type="text">
        <button type="submit">Add City</button>
    </form>
</template>

Template.addcityform.events({
    "submit form": function(event, template) {
        event.preventDefault();
        Cities.insert({
            city: template.find(".city").value,
            population: template.find(".population").value
        });
    }
});

Meteor 模板最酷的地方在于,其中使用的 css 选择器是当前模板的本地选择器,这意味着“提交表单”将始终引用“封闭模板中表单元素的提交事件”,因为您只有一个模板中的表格。 这同样适用于模板实例 .find 方法:它将返回一个与模板或其子模板中的 css 选择器匹配的元素。 这允许您拥有多个彼此独立的 addcityform 实例。

关于forms - Meteor:如何在一组表单字段中接受用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389836/

相关文章:

javascript - Iron 路由器使用 Meteor.call 进行操作时会抛出 writeHead 不是函数

node.js - 如何从unity连接NodeJS数据库?

javascript - 在 Meteor 中获取或创建

javascript - meteor 数二的收藏值(value)

javascript - 如何使用 Javascript 或 jQuery 表单编辑 .txt 文件

Javascript Submit 未将 SUBMIT POST 发送到 php 文件

javascript - 如何清除加载ajax的表单?

javascript - Meteor 发送给活跃用户

oracle - PL/SQL 输入验证技术/实用程序

javascript - 表单提交与 Javascript POST 请求