Meteor-forms
提供:Dev Guides
流星-フォーム
この章では、Meteorフォームを操作する方法を学習します。
テキスト入力
最初に、テキスト入力フィールドと送信ボタンを持つ form 要素を作成します。
meteorAppl
<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 変数に割り当てます。
次の例では、そのコンテンツのみを開発者コンソールに記録します。 そして最後に必要なことは、入力フィールドをクリアすることです。
meteorApp.js
if (Meteor.isClient) {
Template.myTemplate.events({
'submit form': function(event) {
event.preventDefault();
var textValue = event.target.myForm.value;
console.log(textValue);
event.target.myForm.value = "";
}
});
}
入力フィールドに「Some text …」と入力して送信すると、コンソールは入力したテキストを記録します。
ラジオボタン
同様の概念をラジオボタンに使用できます。
meteorAppl
<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>
meteorApp.js
if (Meteor.isClient) {
Template.myTemplate.events({
'submit form': function(event) {
event.preventDefault();
var radioValue = event.target.myForm.value;
console.log(radioValue);
}
});
}
最初のボタンを送信すると、コンソールに次の出力が表示されます。
チェックボックス
次の例は、チェックボックスの使用方法を示しています。 同じプロセスを繰り返していることがわかります。
meteorAppl
<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>
meteorApp.js
if (Meteor.isClient) {
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);
}
});
}
フォームが送信されると、チェックされた入力は true として記録され、チェックされていない入力は false として記録されます。
ドロップダウンを選択
次の例では、 select 要素の使用方法を学習します。 change イベントを使用して、オプションが変更されるたびにデータを更新します。
meteorAppl
<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>
meteorApp.js
if (Meteor.isClient) {
Template.myTemplate.events({
'change select': function(event) {
event.preventDefault();
var selectValue = event.target.value;
console.log(selectValue);
}
});
}
3番目のオプションを選択すると、コンソールはオプション値を記録します。