我试图创建一个动态选择菜单,您可以在其中选择一个客户,然后过滤该客户的联系人。
当我选择客户时,它会正确过滤联系人,但客户选择菜单并未显示已选择任何内容。
<template name="newLeadForm">
<form id="lead">
<fieldset>
<legend>New Lead</legend>
<br/>
<select id="customer_id" class="span12">
<option id="null" value="null">Select One</option>
{{#each customers}}<option id="{{id}}" value="{{_id}}">{{name}} - {{city}}, {{state}} {{zip}}</option>{{/each}}
</select>
<select id="contact_id" class="span12">
<option id="null" value="null">Select One</option>
{{#each contacts}}<option id="{{id}}" value="{{_id}}">{{first_name}} {{last_name}}</option>{{/each}}
</select>
<input id="submit" type="submit" class="btn">
</fieldset>
</form>
</template>
以下是提供给模板的数据
Template.newLeadForm.customers = function () {
return Customers.find();
};
Template.newLeadForm.contacts = function () {
console.log(Session.get("_customer_id"));
return Contacts.find({customer_id: Session.get("_customer_id")});
};
和事件处理程序
Template.insert.events({
'change form#lead #customer_id' : function (event) {
customer = $("form#lead #customer_id").val();
Session.set("_customer_id", $("form#lead #customer_id").val());
},
'submit form#lead' : function (event) {
if (event.type === 'click' || event.type === 'submit') {
event.preventDefault();
var customer_id = $("#customer_id").val();
var contact_id = $("#contact_id").val();
var lead_source_id = $("#lead_source_id").val();
var lead_number = $("#lead_number").val();
if(Leads.insert({id: Leads.find().count() + 1, customer_id: customer_id, contact_id: contact_id})) {
$("#customer_id").val(null);
$("#contact_id").val(null);
Session.set("_customer_id", null);
}
}
}
});
答案 0 :(得分:2)
在Meteor重新渲染select元素中的选项元素之后,您应该告诉它在select元素上设置selectedIndex
属性以便更新它。您可以使用rendered
事件执行此操作:
Template.newLeadForm.rendered = function() {
$("#customer_id")[0].selectedIndex = 5; // possibly track the index so you know what to set it to
}
答案 1 :(得分:0)
简单的解决方法:
Template.newLeadForm.rendered = function(){
$('#customer_id').val(Session.get("_customer_id"))
}
由于newLeadForm
依赖于Session [“_ customer_id”],每当Session [“syntax”]发生变化时,它都会被重新呈现,因此每次Session [“syntax”]都会调用template.hello.rendered
]改变。
<小时/> 另一个选项是,您可以为要保持更新的每个选择添加自动运行:
if (Meteor.isClient){
Meteor.startup(function() {
Deps.autorun(keep_cust_select_updated)
})
function keep_cust_select_updated(){
$('#customer_id').val(Session.get("_customer_id"))
}
}
每当调用Session.set("_customer_id", xxxx)
时,keep_select_updated将重新运行(因为它取决于Session.get("_customer_id")
)并且将选择正确的值(通过jQuery $('#customer_id').val(...)
调用)。
后一种方法的优点是您无需在每个"selected"
<option>