简体   繁体   中英

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

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.

<%= 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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