Processing computations following the completion of page rendering on Rails

I'm working on generating a report with multiple columns. Once the report is rendered, I need to allow users to input a value that will be subtracted from an existing column. With several rows of data, I've attempted the following approach in my views page:

<script>
  function sum() {
  var txtFirstNumberValue = document.getElementById('txt1').value;
  var txtSecondNumberValue = document.getElementById('txt2').value;
  var result = parseFloat(txtFirstNumberValue) - parseFloat(txtSecondNumberValue);
   if(!isNaN(result))  {
   document.getElementById('txt3').value = result;  } }
</script>
<% @arr.each do |j| %>
<% @q =[] %>
<% t= 0 %>
<%= form_for ProductionReport.new ,:url=>{:controller=>"users",:action=>"rate_per_unit_report" } do |i| %>
<tr>
<td><%= j[0] %></td>
<td><%= j[1] %></td>
<td><%= j[2] %></td>
<% @q << j[3] %>
<td><%= i.text_field j[3], :value=>@q[t], :id=>"txt1", :onkeyup=>"sum()", :class=>"txt" %></td>
<td><%= i.text_field :selling_price, :id=>"txt2", :onkeyup=>"sum()", :class=>"txt" %></td>
<td><%= i.text_field :profit_loss, :id=>"txt3", :class=>"txt", :readonly =>true %></td>
<% end %>
<% t = t+1 %>
<% end %>
<td>total</td>
<td><%= @total %></td>
<td><%= @total1 %></td>
<td><%= @total2 %></td>

In my controller:

def rate_per_unit_report
  @user=User.new
  @user = User.find(session[:user_id]).name
  @rpus = params[:production_report][:intial_date]
  @rpue = params[:production_report][:final_date]
  @production_report = ProductionReport.where(:date => @rpus..@rpue)
  @production = @production_report.select(:finished_goods_name).uniq
  @arr=[]
  g = 0
  @production.each do|i|
    @p = @production_report.pluck(:issue_id)
    @ll = @production_report.where(:finished_goods_name=>i.finished_goods_name).select(:total_no_of_items_produced).sum :total_no_of_items_produced
    @k = Issue.where(:id=>@p).pluck(:consolidated_cost)
    @rate = @k[g].to_f / @ll.to_f
    @r = @rate.round(2)
    @arr<<[i.finished_goods_name]+[@ll]+ [@k[g]] + [@r]
    g = g+1
  end
  @<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="10647f64717c2d507162623e797e7a757364">[email protected]</a>(0){|sum,x| sum + x[1].to_i }
  @<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="52263d26333e636f123320207c3b3c38373126">[email protected]</a>(0){|sum,y| sum + y[2].to_i }
  @<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="01756e75606d333c416073732f686f6b646275">[email protected]</a>(0){|sum,z| sum + z[3].to_i }
end

The sample output page displays: []

To subtract the fifth column from the fourth column, I am looking for guidance on how to achieve this.

If further information is needed, please don't hesitate to let me know. Thank you.

Answer №1

Develop JavaScript 'objects' that correspond to each individual row in a table. Monitor specific events in the 5th column such as onchange, onkeyup, or any other event that is appropriate. Extract data from the 4th and 5th columns within the event listener, and perform necessary calculations. The crucial aspect here is to define each row as a distinct object with its own collection of functions and event handlers.

To simplify this process, consider placing each row into a partial and utilizing a script tag to initialize the object for every row.

Below is a starter example assuming you are using jQuery:

RowEntry = function(element) {
  this.$el = element; // pass the row as a jQuery element
  this._init();
}

RowEntry.prototype._init = function() {
  var _this = this; // for referencing 'this' inside anonymous functions

  this.$el.find(".selling-price").on("keyup", function(event) {
    // Perform calculations or call functions here
    // Access 'this' as '_this' within this section
  });

  // Additional event listeners can also be set up if needed
}

In your partial file, include something like:

<script>
  var row = $(".row-entry") // Introduce a reference to the specific row
  new RowEntry(row);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing a function as a value to modify the state within ReactJS

Seeking to enhance the button functionality in my app's list, where clicking UP swaps a list item with the one above it. Initially attempted using a function as a value of the state in setState. Encounter an error upon button click: TypeError: Can ...

JavaScript Deviance

I am facing an issue with my JS code while trying to send form data to a .php file via AJAX. The problem occurs when the input fields are filled - for some reason, my client-side page refreshes and the php file does not get executed. However, everything wo ...

Transmit a continuous flow of integer values from an Android application and capture them on a Node.js express server

I'm looking to develop a simple solution to send a continuous stream of integers from an Android App to a Node.js server. I'm interested in understanding how to establish this stream in Android and how to receive it on my Node.js server using ex ...

Unable to receive data from jQuery AJAX request

I'm feeling a little puzzled at the moment. Whenever I run my ajax call, the error function is triggered every time. I am aware that the data is returning as JSON, and I have set the datatype as jsonp to enable cross-origin functionality. I am not sur ...

Alter the views of a bootstrap date picker in real-time

Is there a way to dynamically change the date picker's view based on different button selections? For example, I have buttons for month, year, and day. Here is what I am trying to achieve: When the month button is selected: I want the date picker ...

Uploading multiple strings to an Amazon S3 bucket using Node.js by piping a string

Suppose I have a simple loop similar to the one shown below: for (const i=0; i<3; i++) { to(`This incrementer is ${i}`) } At the end of the loop, I expect my file to contain: This counter is 0 This counter is 1 This counter is 2 I at ...

What is the method for sending data to routes in vue.js 2 using the get method?

Here is the code snippet for my ajax request: <script> new Vue({ ... methods: { fetchItems: function (page) { var data = {page: page}; this.$http.get('api/items', data).then(f ...

Synchronizing the DOM with the Database in a React Component/View: A Step-by-Step

I recently developed a list component in React, but I'm facing two significant challenges. Although the item gets removed from the database, the change is only visible after refreshing the page. You might have noticed that the list number or ID colu ...

Issue: Wed Nov 06 2019 19:50:56 GMT+0500 (Uzbekistan Standard Time) cannot be used as a React child

Just getting started with react and giving it a try, but I've hit a stumbling block. I wrote some JavaScript, however I keep encountering the mentioned error: class Content extends Component { constructor() { super(); this.date = {new Date ...

Executing the main process function

One of the challenges I'm facing is calling a function from the main process in Javascript while a button is clicked in another file. Here is the code snippet: Main.js const electron = require( 'electron') const {app, BrowserWindow} = elec ...

Obtaining a specific item from a group using AngularJS. Utilizing a declarative method

Consider a scenario where you need to apply a CSS rule to a specific element within a collection that needs to be selected. <div ng-repeat="fragments" ng-click="makeSelected()"></div> $scope.fragments = [ {id: 6379, someProperty: "someValu ...

What could be causing my overloaded controller methods to not be receiving requests correctly?

Within my view, I have a page called PrintPatientConsent.aspx that I need to call for two different types. However, only the default action method is being called by default, even when passing parameters. Here is the code snippet for reference: [Accept ...

Having trouble with JavaScript's XMLHttpRequest returning an 'undefined' string on the first run of my script. I need to find a way to ensure that it loads correctly during

Before we dive in, a quick disclaimer: My knowledge of JS is limited, and I typically learn on the go when creating scripts. However, my usual method didn't work this time. Currently, I'm working on a small JS script that will function as a book ...

Extracting data from nested objects array in React: A step-by-step guide

I am facing an interesting challenge. Currently, I am immersing myself in learning react and have managed to retrieve data from a demo API that I created using Java Spring. Although I am successfully receiving the data in React, my struggle lies in creati ...

Helping JavaScript determine my current location on the website

One issue I am facing is with a single template file that renders pages that may look similar but have slightly different behaviors. The header and text boxes are filled by the template language, while the canvas content distinguishes the pages. Different ...

What is the proper way to execute this API request and retrieve the latest news data using the Fetch method?

Note: Please note that the API Key used in this code is not a real one for privacy reasons. const url = 'http://newsapi.org/v2/everything?' + 'q=platformer&' + 'apiKey=3ce15c4d1fd3485cbcf17879bab498db'; ...

Looking to have the text centered both vertically and horizontally within an <a> tag

I have a created an <a> element that links to JavaScript, but I want it to look like a button. <a href="javascript:void(0)" id="closebtn" onclick="closeNav()">&times;</a> Here is the CSS code: #closebtn ...

Using the jqueryRotate plugin to rotate an image by 90 degrees

Is there a way to rotate images on a webpage using the JQueryRotate script? I have 10 images that I want to be able to rotate when clicked, but I'm not sure how to implement it. Any assistance would be welcomed. This is the HTML code for the images: ...

Is there a way to remove the jQuery .css() upon clicking a different button?

I am currently working on a jQuery switch where I want the clicked button to revert back to its original state when another button is clicked. Additionally, I want the 'OFF' button to be automatically clicked first when the page loads. Despite tr ...

Incorporating Javascript into a Django template: best practices

Using Django templates, I am interested in embedding a Bokeh plot by using Json output. The Json output is already prepared for querying the database. The plot needs to be displayed in a div with a specific ID. According to the documentation, the followi ...