根据Ruby on Rails中的另一个下拉菜单更改下拉菜单

时间:2018-06-29 03:35:38

标签: javascript jquery ruby-on-rails

当前,我的表单看起来像:

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

我想在我的删除列之后添加另一个<td>,提示用户选择付款方式:

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

这将更改行:

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

并且将变为:

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

通过这种方式-用户可以轻松更改他们正在执行的交易类型,而不必重定向到新表格。关于如何实现此目标的任何想法?

1 个答案:

答案 0 :(得分:1)

1 =>删除链接后为交易类型添加选择选项

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

2 =>在select_field上添加一个唯一ID,该ID将在更改交易类型时动态触发

<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 =>使用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>