Home > front end >  How to dynamically get value of input fields in ruby active admin form
How to dynamically get value of input fields in ruby active admin form

Time:08-26

I have this form in rails and I am using active admin form to take inputs. I want to make the form dynamic according to values selected in form.

active_admin_form_for('', :post) do |f|
      f.inputs do
        f.input :type_dropdown, as: :select, collection: %w(state zipcode), name: :type_dropdown, required: true, include_hidden: false
        f.input :state_value, name: :state_value, required: true. #I want this input field to show only if state is selected in dropdown above, otherwise I want it hidden
        f.input :zipcode_value, name: :zipcode_value, required: true
      end
      f.actions do
        f.submit "Submit"
      end
    end
end

CodePudding user response:

After going through a lot of answers found this solution, we have to use jquery here. We have to write our jquery code in app/admin/assets/active_admin.js.

My jquery code in active_admin.js looks like this -

 $(document).on("change", "select.type-dropdown", function (){
     let dropdown_value = $(this).val()
     $('.state-value').val(dropdown_value)
 })

And my form now looks like this -

    active_admin_form_for('', :post) do |f|
      f.inputs do
        f.input :type_dropdown, as: :select, collection: %w(state zipcode), name: :type_dropdown, required: true, include_hidden: false, input_html: {class: "type-dropdown"}
        f.input :state_value, name: :state_value, required: true, input_html: {class: "state-value"}
        f.input :zipcode_value, name: :zipcode_value, required: true
      end
      f.actions do
        f.submit "Submit"
      end
    end

Hope this helps in how to include jquery with active admin.

  • Related