rails -nested_form_for 中的动态选择菜单 [英] rails - dynamic select menus within nested_form_for

查看:38
本文介绍了rails -nested_form_for 中的动态选择菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以通常的方式使用nested_form_for,但我想向嵌套的子项添加动态选择菜单.

I'm using the nested_form_for in the usual way but I want to add dynamic select menus to the nested children.

我有以下咖啡脚本(改编自 'dynamic-select-menus' railscast)

I have the following coffee script (adapted from the 'dynamic-select-menus' railscast)

jQuery ->
  $( ".controls-row" ).each ->
    $(this).bind "change", ->
      type = $('#expense_type :selected').text()
      if (type == "miles")
        $('#amount_currency').hide()
        $('#km_traveled').show()
      else 
        $('#amount_currency').show()
        $('#km_traveled').hide()

这段代码的问题是它只适用于第一个嵌套元素.我尝试为每个元素添加唯一的 id,但这仅适用于现有元素.新元素都是蓝图"元素的克隆,并且都具有相同的 ID.

the problem with this code is that it will only work with the first nested element. I tried adding unique id's to each of the elements but that only works for existing elements. New elements are all clones of the 'blueprint' element and will all have the same ID.

有没有人有更好的方法在嵌套表单中实现动态选择菜单?

Does anyone have a better way of implementing dynamic select menus within nested forms?

推荐答案

我用这个代码解决了它:

I soved it with this code:

jQuery ->
  $(document).on "nested:fieldAdded", (event) ->
    $( ".controls-row" ).each ->
        $(this).find('#expense_type').bind "change", ->
            type = $(this).parent().find('#expense_type :selected').text()
            if (type == "km")
                $(this).parent().find('#payment_method').addClass('hidden').hide()              
                $(this).parent().find('#amount_in_currency').addClass('hidden').hide()
                $(this).parent().find('#amount_currency').addClass('hidden').hide()
                $(this).parent().find('#km_traveled').removeClass('hidden').show()
            else 
                 $(this).parent().find('#payment_method').removeClass('hidden').show()
                 $(this).parent().find('#amount_currency').removeClass('hidden').show()
                 $(this).parent().find('#amount_in_currency').removeClass('hidden').show()
                 $(this).parent().find('#km_traveled').addClass('hidden').hide()
        $(this).find('#expense_type').trigger('change')

  $(document).trigger("nested:fieldAdded")

这篇关于rails -nested_form_for 中的动态选择菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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