根据rails collection select(selected)项显示不同的控件

时间:2014-04-23 11:08:15

标签: javascript ruby-on-rails

抱歉,我无法获得更好的问题标题,但希望我的解释会让你们更好地了解发生了什么?

我有一个模型Airport和其他三个模型West EastSouth,但这些模型只与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中选择机场西,则应显示west-airports div`,依此类推。但是我的验证方法机场不断为: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_selects,但仍然会收到验证错误或获得持久值。

1 个答案:

答案 0 :(得分:0)

您的表单包含多个具有相同名称的元素(:airline_name),这是核心问题。您已停用正确的轨道并禁用,但您要禁用div而不是选择。我会这样做:

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