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

时间:2013-08-22 20:03:52

标签: forms 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的示例,但由于可能存在名称空间冲突,这对我来说似乎很笨拙。我想以“正确的方式”执行此操作,以便稍后可以扩展,例如,我可以将表单的多个实例放在页面上,它们应该彼此独立。这样做的“正确方法”是什么?

1 个答案:

答案 0 :(得分:6)

您在“提交表单”处理程序中缺少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的多个实例,这些实例将彼此独立。