Ad

Select_tag Rails, Display Value Dynamically Before Submit

- 1 answer

I have a form showing some available banks I can choose, using a select_tag. The selected bank is stored in params[:bank] when I submit the form

What I want to do is to dynamically show information about the selected bank before submitting. Basically, if I chose "Bank 1", I want to display bank 1 information. If I select Bank 2, I want to display bank 2 information. And when I am happy, I submit.

Here is my code

<%= form_tag final_payments_path, method: :get do %>

  <%= select_tag "bank", options_from_collection_for_select(Bank.active, "id", "name") %>

  <%= button_tag( class: "btn-continue-displayed mt-3") do %>
   <i class="fas fa-caret-left"></i><p>Approve</p>
  <% end %>
<% end %>

How can I dynamically find the selected option before submitting and display the information?

My first step was to add onchange: "alert(this.value)" on my select tag. It works and shows the id. If I change and put

 options_from_collection_for_select(Bank.active, "IBAN", "name")

it shows an alert with the IBAN. Which is a good start.

Is there a way I can put 3 elements (id, IBAN and SWIFT) in the value instead of only one?

Thanks a lot for your help

Ad

Answer

You can find bank id via js:

$('#select_tag_id').on('change', function () {
    let bank_id = $(this).val();
});

bank_id will contain id of selected bank.

routes.rb:

  get "/selected_bank" => 'your_controller#show_info'

Then:

$('#select_tag_id').on('change', function () {
      let bank_id = $(this).val();
      $.ajax({
          data: {bank_id: bank_id},
          url: '/selected_bank',
          type: 'GET'
      });
  });

Your controller:

def show_info
  @bank = Bank.find(params[:bank_id])
  respond_to { |format| format.js }
end

_info.html.erb:

<div class="info">
  <p>
    Id:
    <%= @bank.id %>
  </p>
  <p>
    Name:
    <%= @bank.name %>
  </p>
</div>

show_info.js.erb:

$('.some-class-on-page').html("<%= j(render 'info') %>");
Ad
source: stackoverflow.com
Ad