Change second select list based on first select list value in rails

后端 未结 1 1078
执笔经年
执笔经年 2020-12-18 04:30

Updated with answer code at bottom

For second select box, show select options for only those staff members associated to the selected <

相关标签:
1条回答
  • 2020-12-18 05:30

    First you fire an ajax call to your controller. (Keep in mind that this url from the ajax call must exist in your routes).

    $(document).ready(function() {
      $("#team").on('change', function(){
        $ajax({
          url: "populate_other_list",
          type: "GET",
          data: {team_id: $(this).val()},
          // Callbacks that will be explained
        })
      });
    

    Next you make your action inside your controller.

    def populate_other_list
      team_id = params[:team_id]
      @staff = Staff.find_by team_id: team_id
      respond_to do |format|
        format.json { render json: @staff }
      end
    end
    

    With this, on your success callback of your ajax call, you get a JSON object with your list. So you need to clear the staff select and create the options and append to it.

    // Ajax call
    success: function(data) {
      $("#staff_member_id").children().remove();
      // Create options and append to the list
    }
    // Rest of Ajax call
    

    As you can see, i didn't put the code that create the options and put them inside the list, but a simple search will have plenty of results about this. The idea is simple though.

    0 讨论(0)
提交回复
热议问题