Dynamic select menu Rails, Javascript HABTM
- by Jack
Hi,
I am following a tutorial in one of Ryan Bates' Railscasts here. Basically I want a form where there are 2 drop down menus, the contents of one are dependent on the other. I have Years and Courses, where Years HABMT Courses and Courses HABTM Years. In the tutorial, the javascript is as follows:
var states = new Array();
<% for state in @states -%>
states.push(new Array(<%= state.country_id %>, '<%=h state.name %>', <%= state.id %>));
<% end -%>
function countrySelected() {
country_id = $('person_country_id').getValue();
options = $('person_state_id').options;
options.length = 1;
states.each(function(state) {
if (state[0] == country_id) {
options[options.length] = new Option(state[1], state[2]);
}
});
if (options.length == 1) {
$('state_field').hide();
} else {
$('state_field').show();
}
}
document.observe('dom:loaded', function() {
countrySelected();
$('person_country_id').observe('change', countrySelected);
});
Where I guess country has many states and state belongs to country. I think what I need to do is edit the first for statement to somehow loop through all of the courses for each year_id, but don't know how to do this. Any ideas?
Thanks