根据轨道集合选择(选定)项显示不同的控件

Show different controls depending on rails collection select (selected) item

本文关键字:显示 控件 选定 轨道 集合 选择      更新时间:2023-09-26

很抱歉我的问题没有更好的标题,但希望我的解释能让你们更好地了解发生了什么?

我有一个模型Airport和三个其他模型WestEastSouth,它们无论如何都不相关,只是Airport模型需要一些其他字段,如此表单所示。

<%= form_for(@airport) do %>
    <%= f.collection_select(:airport_name, AirPortManager.all, etc...) %>
      //AirPortManager is a collection of available airports
    <div class="west-airports" style="display:none;">
        <%= f.collection_select(:airline_name, WestAirlineManager.all, ....) %>
    </div>
    <div class="east-airports" style="display: none;">
        <%= f.collection_select(:airline_name, EastAirlineManager.all, ....) %>
    </div>

    <div class="south-airports" style="display: none;">
        <%= f.collection_select(:airline_name, EastAirlineManager.all, ....) %>
    </div>
 <% end %>

机场型号validates :airline_name, :presence => true。现在问题出在上

我的javascript。如果用户在AirPortManager.all中选择了airport west,则应显示west-airportsdiv`,依此类推。但我的验证方法airport不断抛出一个必需的字段错误:airline_name,如果不是,则保留以前选择的值。我如何将可见的div值传递给机场参数,或者如果我选择了一个空值,则前一个值不应保持不变。下面是我的javascript,希望我的问题有意义。

<script type="text/javascript">
    $(document).ready(function() {
             $("#aiport_manager_aiport_name").change(function(){
                var value = this.value;
                if (value == "West") {
                     $('.west-aiports').show();
                    $('.east-airports').attr("disabled", true);
                    $('.east-airports').hide();
                     $('.south-airports').attr("disabled", true);
                     $('.south-airports').hide();
                    }
                else if (value == "East") {
                    $('.east-airports').show();
                    $('.west-aports').hide();
                    $('.west-airports').attr("disabled", true);
                    $('.south-airports').hide();
                    $('.south-airports').attr("disabled", true);
                    }
                else if (value == "South") {
                    $('.south-aiports').show(); 
                    $('.west-airports').hide();
                    $('.west-airports').attr("disabled", true);
                    $('.east-airports').hide();
                    $('.east-airports').attr("disabled", true);
                    }
                });
            });
</script>

我尝试在它们各自的div中禁用其他collection_selections,但仍然会得到一个验证错误或一个持久值。

您的表单有多个名称相同的元素(:airline_name),这是核心问题。禁用是正确的,但您禁用的是div而不是select。我会这么做:

// before form is submitted, disable all hidden selects
$('form').on('submit', function(e) {
  $('select:hidden').prop('disabled', true);
});