Rails Multiple Checkboxes with Javascript Dynamic Select

Posted by Jack on Stack Overflow See other posts from Stack Overflow or by Jack
Published on 2010-05-14T10:12:28Z Indexed on 2010/05/14 10:14 UTC
Read the original article Hit count: 408

Filed under:
|

Hi,

I have followed the Railscast episode 88 to implement a set of dependant drop down menus. In the students->new view, when the student's year is selected, the javascript figures out which courses are available to that year and offers the selection in a new drop down menu.

My javascript erb file is here:

var courses = new Array();
<% for course in @courses -%>
    <%for year in course.years -%>
        courses.push(new Array(<%= year.year_id%>, '<%=h course.title%>', <%= course.id%>));
    <%end -%>
<% end -%>

function yearSelected() {
    year_id = $('student_year_id').getValue();
    options = $('student_course_ids').options;
    options.length = 1;
    courses.each(function(course) {
        if (course[0] == year_id) {
            options[options.length] = new Option(course[1], course[2]);
        }
    });
    if (options.length == 1) {
        $('course_field').hide();
    } else {
        $('course_field').show();
    }
}

document.observe('dom:loaded', function() {
  yearSelected();
  $('student_year_id').observe('change', yearSelected);
});

Any my view is as follows:

<% form_for(@student) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :cid, "CID" %><br />
    <%= f.text_field :cid %>
  </p>
  <p>
    <label for="student_year_id">Year:</label>

    <%= collection_select(:student, :year_id, Year.all, :id, :title, {:prompt => true})%>
  </p>

  <p id="course_field">
    <label for="student_course_ids">Course:</label>
    <%= collection_select(:student, :course_ids, Course.find(:all), :id, :title, {:prompt => true}, {:multiple => true})%>

  </p>
  <p>
    <%= f.submit 'Save' %>
  </p>
<% end %>

What I would like to do is to add checkboxes instead of the drop down menu. Any suggestions? I previously was using this method, but was not able to get it to work with the new javascript.

Cheers

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about JavaScript