<head> <title>meteorApp</title> </head> <body> <div> {{> myTemplate}} </div> </body> <template name = "myTemplate"> <form> <input type = "text" name = "myForm"> <input type = "submit" value = "SUBMIT"> </form> </template>
在JavaScript文件中,咱們將建立 submit 事件。咱們須要防止默認事件的行爲以中止刷新瀏覽器。下一步,咱們要使用輸入字段的內容,並將其文本值賦值給變量 textValue 。 在這個例子中,咱們只記錄了內容輸出到開發者控制檯。最後一件事是明確的輸入字段。html
import { Template } from 'meteor/templating'; Template.myTemplate.events({ 'submit form': function(event){ event.preventDefault(); var textValue = event.target.myForm.value; console.log(textValue); event.target.myForm.value = ""; } });當咱們在輸入欄中鍵入「一些文字...」,而後點擊提交。控制檯將記錄下咱們輸入的文本。
<head> <title>meteorApp</title> </head> <body> <div> {{> myTemplate}} </div> </body> <template name = "myTemplate"> <form> <input type = "radio" name = "myForm" value = "form-1">FORM 1 <input type = "radio" name = "myForm" value = "form-2">FORM 2 <input type = "submit" value = "SUBMIT"> </form> </template>
import { Template } from 'meteor/templating'; Template.myTemplate.events({ 'submit form': function(event){ event.preventDefault(); var radioValue = event.target.myForm.value; console.log(radioValue); } });當咱們提交的第一個按鈕,控制檯會顯示如下輸出。
<head> <title>meteorApp</title> </head> <body> <div> {{> myTemplate}} </div> </body> <template name = "myTemplate"> <form> <input type = "checkbox" name = "myForm" value = "form-1">FORM 1 <input type = "checkbox" name = "myForm" value = "form-2">FORM 2 <input type = "submit" value = "SUBMIT"> </form> </template>
Template.myTemplate.events({ 'submit form': function(event){ event.preventDefault(); var checkboxValue1 = event.target.myForm[0].checked; var checkboxValue2 = event.target.myForm[1].checked; console.log(checkboxValue1); console.log(checkboxValue2); } });當提交表單,雖然它們未選中一個那麼將會被記錄爲 false,若是有選中一個檢查輸入將被記錄爲 true 。
在這個例子中,咱們將展現如何使用select元素。咱們將使用更改事件,以每次變化更新數據的選項。swift
<head> <title>meteorApp</title> </head> <body> <div> {{> myTemplate}} </div> </body> <template name = "myTemplate"> <select> <option name = "myOption" value = "option-1">OPTION 1</option> <option name = "myOption" value = "option-2">OPTION 2</option> <option name = "myOption" value = "option-3">OPTION 3</option> <option name = "myOption" value = "option-4">OPTION 4</option> </select> </template>
if (Meteor.isClient) { Template.myTemplate.events({ 'change select': function(event){ event.preventDefault(); var selectValue = event.target.value; console.log(selectValue); } }); }