How to populate a Rails dropdown menu with a json array

后端 未结 1 1476
隐瞒了意图╮
隐瞒了意图╮ 2021-01-07 03:25

I have an Ant show page that displays detailed information about various types of ants. On that page there are two drop downs, one for environment: [indoor, outdoor], and on

相关标签:
1条回答
  • 2021-01-07 03:59

    It seems to me like you want to dynamically populate the dropdown box, which would lend itself to an ajax call, like this:

    $('#select_box').on('change', function () {
        $.ajax({
            url: "/controller/action",
            type: 'get',
            data: $(this).serialize()
        }).done(function (data) {
            change_select(data);
        });
    });
    
    function change_select(data) {
        var json = jQuery.parseJSON(data);
        var options = [];
        json.each(function (key, index) {
            options.push({text: index, value: key});
        });
        $("#select_box").replaceOptions(options);
    };
    

    This will allow you to specify the options of the dropdown, and you can use the controller in this way:

      @food_sources = Ant.find(params[:ant_id]).product_recommendations.where(environment: params[:environment]).map(&:diet)
      respond_to do |format|
        format.json { render json: @food_sources }
      end
    
    0 讨论(0)
提交回复
热议问题