我正在尝试在我的Rails应用程序中使用动态选择菜单。
我有一个名为kase的模型,一个名为person的模型和一个名为company的模型。
当用户创建新的kase时,会向他们显示一个选择字段以选择一个人,并选择一个选择字段来选择一个公司。
我试图让它变得动态,所以如果他们在第一个选择字段中选择公司a,那么只有公司a的员工才会列在人员字段中。
模型关联如下:
class Kase < ActiveRecord::Base
belongs_to :company # foreign key: company_id
belongs_to :person # foreign key in join table
belongs_to :surveyor,
:class_name => "Company",
:foreign_key => "appointedsurveyor_id"
belongs_to :surveyorperson,
:class_name => "Person",
:foreign_key => "surveyorperson_id"
-------------------------------------------------
class Company < ActiveRecord::Base
has_many :kases
has_many :people
def to_s; companyname; end
-------------------------------------------------
class Person < ActiveRecord::Base
has_many :kases # foreign key in join table
belongs_to :company
更新JAVASCRIPT
var people = new Array();
<% for person in @people -%>
people.push(new Array(<%= person.company_id %>, '<%=h person.personname %>', <%= person.id %>));
<% end -%>
function personSelected() {
alert('hello world');
appointedsurveyor_id = $('kase_appointedsurveyor_id').getValue();
options = $('kase_surveyorperson_id').options;
options.length = 1;
people.each(function(person) {
if (person[0] == appointedsurveyor_id) {
options[options.length] = new Option(person[0], person[1]);
alert('hello world')
}
});
if (options.length == 1) {
$('kase_surveyorperson_id').hide();
} else {
$('kase_surveyorperson_id').show();
}
}
document.observe('dom:loaded', function() {
$('kase_appointedsurveyor_id').observe('change', personSelected);
});
答案 0 :(得分:1)
var people = new Array();
<% for person in @people -%>
people.push(new Array(<%= person.id %>, '<%=h person.login %>'));
<% end -%>
function personSelected() {
alert('hello world');
appointedsurveyor_id = $('company_appointedsurveyor_id').getValue();
options = $('person_appointedsurveyorperson_id').options;
options.length = 1;
people.each(function(person) {
if (person[0] == appointedsurveyor_id) {
options[options.length] = new Option(person[0], person[1]);
}
});
if (options.length == 1) {
$('person_field').hide();
} else {
$('person_field').show();
}
}
document.observe('dom:loaded', function() {
//companySelected(); << remove this
$('person_field').observe('change', personSelected);
});
答案 1 :(得分:0)