我有一个简单的表单,有两个输入:“ title”和_“ description”,以及两个按钮:“ save”(保存以供以后使用)和“ submit”。对于这两种方式,我都希望获取表单字段的值并相应地插入/更新集合。
<template name="NewScenarioForm">
<form id="newScenarioForm" >
<textarea type="text" id="title" name="title" rows="1" cols="75" placeholder="Type to add a title"></textarea><br/>
<textarea type="text" id="description" name="description" rows="4" cols="100" placeholder="Type to add a description" ></textarea><br/>
<input type="submit" id="saveScenarioButton" name="action" title="Save Scenario" value="Save" />
<input type="submit" id="submitScenarioButton" name="action" title="Submit for approval" value="Submit" />
</form>
</template>
现在,我正在检测这样的事件:
"click #saveScenarioButton": function(event, template) {
event.preventDefault();
var title = template.find("#title").value;
var description = template.find("#description").value;
...
//Do stuff with this information to persist information
Meteor.call("saveScenario", title, description);
....
}
我需要为另一个按钮重复整个功能。我想检测该事件并确定按下了哪个按钮。
我一直在努力与类似的事件处理程序:
"submit #newScenarioForm": function(event) {
但是然后我不知道如何确定单击的按钮,因为我无法确定事件属性。如果我想在事件处理程序中使用表单ID而不是每个按钮的ID,是否可以确定按钮(或者是一种更智能的方法)?
您可以使用类型Submit作为事件目标输入:
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
// Save the scenario
} else if ($(e.target).prop("id") == "submitScenarioButton") {
// Submit the scenario
}
}
});
您也可以让它检查单击的按钮的值,然后删除ID字段
请注意,这不会处理提交表单的其他方式,例如,用户在输入字段中按Enter。处理此问题的一种方法可能是定义一些函数:
function scrapeForm() {
// Collects data from the form into an object
}
function saveData() {
var formData = scrapeForm();
// More logic to save the data
}
function submitData() {
var formData = scrapeForm();
// More logic to submit the data
}
Template.NewScenarioForm.events({
"click input[type=submit]": function(e) {
if ($(e.target).prop("id") == "saveScenarioButton") {
saveData();
} else if ($(e.target).prop("id") == "submitScenarioButton") {
submitData();
}
},
"submit #NewScenarioForm":
// Default action on submit.
// Either save the data
saveData
// or submit the data
submitData
// or nothing, requiring the user to actually click one of the buttons
function(e) {e.preventDefault();}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句