简体   繁体   English

如何将Ruby on Rails的“ form_for”元素传递给Javascript函数?

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

I want to create a function that adds the value of a text field to another, the problem here is that I'm using forms from Ruby on Rails and I don't know if it is possible to get the ID from the field I want to process. 我想创建一个将文本字段的值添加到另一个字段的函数,这里的问题是我使用的是来自Ruby on Rails的表单,我不知道是否有可能从我想要的字段中获取ID处理。 Here is my code: 这是我的代码:

This is a nested form. 这是一个嵌套形式。

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

And here is my javascript function: 这是我的JavaScript函数:

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

You can pass this which will represent the field you want. 您可以通过this字段,该字段将代表您想要的字段。

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

and then in your function you can do: 然后在您的函数中,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM