rails - dynamic select menus within nested_form_for

六眼飞鱼酱① 提交于 2019-12-12 09:08:53

问题


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

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()

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?


回答1:


Just use a regular expression to change the 'blueprints' id to something unique.

For example, if you are loading a partial you can use Javascript's replace to change the default ID.




回答2:


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")


来源:https://stackoverflow.com/questions/13355837/rails-dynamic-select-menus-within-nested-form-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!