如何传递Ruby on Rails 'form_for'元素到Javascript函数

How to pass Ruby on Rails 'form_for' elements to a Javascript function?

本文关键字:元素 for Javascript 函数 form Rails Ruby 何传递 on      更新时间:2023-09-26

我想创建一个函数,将文本字段的值添加到另一个,这里的问题是我正在使用Ruby on Rails的表单,我不知道是否可以从我想要处理的字段中获得ID。下面是我的代码:

这是一个嵌套表单。

<%= f.fields_for :invoices do |invoice_form| %>
  <br>
    <%= invoice_form.label :in_number %>
    <br>
    <%= invoice_form.text_field :in_number %>
    <br>
    <%= invoice_form.label :in_amount %>
    <br>
    <%= invoice_form.text_field(:in_amount,:onkeypress => "myFunction(document.getElementById('in_amount'))") %>
    <br>
    <%= invoice_form.label :in_date %>
    <br>
    <%= invoice_form.date_select :in_date %>
    <br>
    <%= invoice_form.label :in_meshHr %>
    <br>
    <%= invoice_form.text_field :in_meshHr %>
  <% end %>

下面是我的javascript函数:

function myFunction(text) {
    var amount = parseFloat($('#purchase_order_po_amount').val());
    var amount1 = document.getElementById(text).value;
    alert(amount1+amount);
}

您可以传递this,它将代表您想要的字段。

<%= invoice_form.text_field(:in_amount,:onkeypress => "myFunction(this)") %>

然后在你的函数中你可以这样做:

function myFunction(element) {
  var amount = parseFloat($('#purchase_order_po_amount').val());
  var amount1 = $(element).val();
  alert(amount1+amount);
}