Jean Malan
Jean Malan

Reputation: 1

Changing dropdown menu based on another dropdown in Ruby on Rails

Currently I have a form that looks like :

<tr>
  <td>
   <%= f.hidden_field :_destroy %>
   <%= link_to "remove", '#', class: "remove_record"
</td>
    <td><%= f.date_field :date, as: :date, value: f.object.try(:strftime,"%m/%d/%Y"), class: 'form-control' %> </td>
    <td><%= f.text_field :description, label: false, class: 'form-control input'  %></td>
    <td><%= f.text_field :reference, label: false, class: 'form-control input'  %></td>
    <td>  <%= f.collection_select :bank_account_id, BankAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm" %></td>
    <td><%= f.collection_select :gl_account_id, GlAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm" %></td>
    <td><%= f.collection_select :vat_type, Transaction.vat_types.map{ |dp| [dp.first, dp.first.humanize] }, :first, :second,{:prompt => false},class:"btn btn-sm"  %></td>
    <td> <%= f.text_field :total_amount, class: 'form-control input'  %></td>
    <%  f.check_box :payment, :value => true %>

</table>

I want to add another <td> after my remove column that prompts a user to select what type of payment it is:

<select> 
  <option value="regular">Regular</option>
  <option value="invoice">Invoice</option>
  </select>

This would change the row:

<td><%= f.collection_select :gl_account_id, GlAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm" %></td>

And will become:

<td><%= f.collection_select :purchase_id, Purchase.all, :id, :invoice_number, {:prompt => false},class:"btn btn-sm" %></td>

This way - the user can easily change the type of transaction they are performing without having to be redirect to a new form. Any ideas on how I can achieve this?

Upvotes: 0

Views: 928

Answers (1)

Anand
Anand

Reputation: 6531

1 => Add a select option for transaction type after remove link

<%=select_tag "transaction_type", options_for_select([['regular', 'Regular'], ['invoice', 'Invoice']]), class: 'transaction_type'%>

2 => Add a unique id on select_field which will be triggered dynamically on change of transaction type

<td><%= f.collection_select :gl_account_id, GlAccount.all, :id, :name, {:prompt => false},class:"btn btn-sm", id: 'gl_account' %></td> 
<td><%= f.collection_select :vat_type, Transaction.vat_types.map{ |dp| [dp.first, dp.first.humanize] }, :first, :second,{:prompt => false},class:"btn btn-sm", id: "vat_type"  %></td>

3 => Using Jquery

<script>
  //by default hide both gl_account and vat_type select box
  $('#vat_type, #gl_account').hide();
  // on change transaction_type show/hide these select box
  $('.transaction_type').on('change', function(){
    var transaction_type_Val = $(this).val();
    if (transaction_type_Val == 'regular'){
      $('#gl_account').show();
      $('#vat_type').hide();
    }else{
      $('#gl_account').hide();
      $('#vat_type').show();
    }
  })
</script>

Upvotes: 2

Related Questions