Select_tag Rails, Display Value Dynamically Before Submit
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
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') %>");
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM