如何基于表单输入添加动态复选框? [英] How to add dynamic checkboxes based on form input?

查看:79
本文介绍了如何基于表单输入添加动态复选框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文 用户可以填写订购单,在该订购单中可以选择bike_type,从而可以选择属于该bike_type的选项.

Context A user can fill in an order form where a bike_type can be chosen and consequently the options belonging to that bike_type.

当前情况 基于simple_form列中的用户输入('bike_type'),我想包括一个带有所有潜在选项('options')的复选框,其中可以选择多个选项.目前,我能够:

Current situation Based on user input ('bike_type') in a simple_form column, I would like to include a checkbox with all potential options ('options) where multiple options can be selected. Currently, I am able to:

  • (情况1)在视图中通过Ajax显示相应bike_type的所有选项,但不幸的是,这些选项未在参数中发送.

  • (Situation 1) Display all the options for the respective bike_type via Ajax in the view, but unfortunately these are not being sent in the params.

(情况2)显示所有自行车的所有选项,这些插入参数并正确保存,但这是不正确的,因为用户应仅能够选择属于bike_type的选项.

(Situation 2) Display all options for all bikes, these are inserted into the params and correctly saved, but this is not correct as users should only be able to select options that belong to the bike_type.

HTML 我认为该错误在于JS在复选框列表中插入选项的情况.我尝试模仿下面显示的html,但似乎无法正确处理.因此,请在下面找到一些HTML差异的打印屏幕.

在以下参数中未正确插入的不正确的html:

Incorrect html that is not inserted properly in the params below:

更正以下插入的html(因为它呈现了所有选项,包括视图中的不同自行车选项):

Correct html that is inserted (As it renders all options incl. different bike options in the view) below:

表格

<%= simple_form_for [@bike_store, @order] do |f|%>
  <%= f.collection_check_boxes :option_ids, Option.all, :id, :name do |b| %>
    <div class="collection-check-box", id='test-options'>
      <%= b.check_box %>
      <%= b.label %>
    </div>
  <% end %>
  <%= f.submit %>
<% end %>

脚本

<script >
  $(document).on("change", "#bike_type", function(){
    var bike_type = $(this).val();

   $.ajax({
    url: "/bike_stores/<%= @bike_store.id %>/orders/new",
    method: "GET",
    dataType: "json",
    data: {bike_type: bike_type},
    error: function (xhr, status, error) {
      console.error('AJAX Error: ' + status + error);
    },
    success: function (response) {
      console.log(response);

      // test
      $("#test-options").html("");
      $("#test-options").append("");
      for(var i=0; i< options.length; i++){
        $("#test-options").append('<input type="checkbox" value="' + options[i]["id"] + '">' + options[i]["name"] + '');
      }
      // test

    }
  });
});
</script>

controller.rb

controller.rb

def new
    @bike_store = BikeStore.find(params[:bike_store_id])
    @order = Order.new
    @orders = @bike_store.orders
    @order.order_options.build
    @options = []

    # Display options for bike_type
    if params[:bike_type].present?
      @options =  BikeType.find(params[:bike_type]).options
    end
    if request.xhr?
      respond_to do |format|
        format.json {
        render json: {options: @options}
      }
    end
  end
    # test
    authorize @order
  end

  def create
    @order = Order.new(order_params)
    @bike_store = BikeStore.find(params[:bike_store_id])
    @order.bike_store = @bike_store
    @order.order_contact = @order_contact
    authorize @order
    @order.save
    redirect_to root_path
  end

private
def set_order
    @order = order.find(params[:id])
  end

  def order_params
    params.require(:order).permit(:arrival, :departure, :order_contact_id,
      order_bikes_attributes: [:id, :bike_id, :bike_quantity, :_destroy,
        bikes_attributes: [:id,:name, :bike_type_id,
          bike_types_attributes: [:id, :name]]],
      order_options_attributes: [:id, :option_id, :option_quantity, :_destroy,
        options_attributes: [:id, :name, :bike_type_id, :description,
          bike_types_attributes:[:id, :name]]])
  end

推荐答案

如果问题仅在于呈现正确的输入字段,则可以采用以下方法:

If the problem is only in rendering the proper input fields, then you may follow this approach:

这是一个代码段,用于根据用户的年龄段来呈现事件的选择选项.相当类似于您的

This is a code snippet to render select options for events based on the user's age group..quite similar to yours:

.done(function (events){

                    var select = document.getElementById( "events-dropdown" );
                        while(select.length >0){
                            select.remove(select.length-1);
                        }
                        var option;
                    if( Object.keys( events ).length > 0){
                        events.forEach(function( event ) {
                                option = document.createElement( 'option' );
                                option.value = event.id;
                                option.textContent = event.title;
                                select.add( option );
                            });
                    }
                    // no events found for particular gender AND age group
                    else{ 
                        option = document.createElement( 'option' );
                        option.value ='';
                        option.textContent= 'Sorry! No events found for your age group';
                        option.disabled = true;
                        select.add( option );
                    }

                    });

这篇关于如何基于表单输入添加动态复选框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆