I am looking to integrate a predefined equation using JavaScript

I need help implementing a specific formula in JavaScript that involves dealing with 5 input fields.

Below is the HTML code (apologies for the language, it is in a different locale):

<div class="row" style="padding:10px 12px;">
                  <div class="row">          
                    <div style="display:flex; justify-content:space-between; flex-wrap:wrap;">
                      <label class="control-label col-lg-6 col-md-6 col-sm-6" for="K">Shkolla e Mesme:</label>
                      <div class="controls">
                        <select name="K" class="span3 col-lg-6 col-md-6 col-sm-6 form-control1" id="K">
                          // Option values go here
                        </select>
                      </div>
                    </div>
                  </div>
                  
                  // Additional input field elements go here
                  
</div>

The formula that needs to be applied is:

{[26 x Field1 + 20 x Field2 + Field3 + Field4)] x 1.4 + 17 x (Field5 x 1.3 + Field6 x 1.2)} x 5

There is a sample code below that might be helpful, but adjustments are needed:

Qty1 : <input onblur="findTotal()" type="text" name="qty" id="qty2"/><br>
// Additional input fields go here
Total : <input type="text" name="total" id="total"/>


    <script type="text/javascript">
function findTotal(){
    var arr = document.getElementsByName('qty');
    var tot=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
    }
    document.getElementById('total').value = tot;
}

    </script>

Any guidance or assistance is greatly appreciated. Thank you.

Answer №1

Retrieve the value entered in each input field.

The value for the first field can be obtained using: field1 = parseInt(document.getElementById('M').value);

Calculate the total value based on your specified formula: var total= 5*((26 * field1 + 20 * field2 + field3 + field4) * 1.4 + 17 * (field5 * 1.3 + field6 * 1.2));

Check out the modified code on JSBin.

function calculateTotal(){
var field1 = parseInt(document.getElementById('M').value);
var field2 = parseInt(document.getElementById('D1').value);
var field3 = parseInt(document.getElementById('D2').value);
var field4 = parseInt(document.getElementById('D3').value);
var field5 = parseInt(document.getElementById('F1').value);
var field6 = parseInt(document.getElementById('F2').value);

var total= 5*((26 * field1 + 20 * field2 + field3 + field4) * 1.4 + 17 * (field5 * 1.3 + field6 * 1.2));

document.getElementById('total').value = total;}

Answer №2

What is your ultimate goal here?
Are you aiming to calculate the result of a formula based on user input and then present it to the user? If so, should this calculation trigger on click, on submit, or on blur?

It seems like this is what you are looking for ...
check out this jsbin (please note that formula values have not been tested)

To streamline your code,

html:

<input id='field-1' type='number' placeholder="field-1" />
<input id='field-2' type='number' placeholder="field-2" />
<input id='field-3' type='number' placeholder="field-3" />
<input id='field-4' type='number' placeholder="field-4" />
<input id='field-5' type='number' placeholder="field-5" />
<input id='field-6' type='number' placeholder="field-6" />
<button onClick=onClick()>Calculate</button>

js:

function onClick () {
  const Field1 = Number(document.getElementById('field-1').value)
  const Field2 = Number(document.getElementById('field-2').value)
  const Field3 = Number(document.getElementById('field-3').value)
  const Field4 = Number(document.getElementById('field-4').value)
  const Field5 = Number(document.getElementById('field-5').value)
  const Field6 = Number(document.getElementById('field-6').value)
  const result = ((26 * Field1 + 20 * Field2 + Field3 + Field4) * 1.4 + 17 * (Field5 * 1.3 + Field6 * 1.2)) * 5
  alert('The result is ' + result)
}

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

unable to use redirect feature for specific URLs with nodejs module

I have been using the request nodejs module to retrieve HTML content from websites. However, I have encountered issues with certain redirection websites, as shown below: var request = require('request'); var options = { url: "http://www.amw ...

Exploring the various methods of creating controllers and services in AngularJS and understanding the rationale behind each approach

I've been observing various instances of controller and service creation in AngularJS and I'm feeling perplexed. Could someone elucidate the distinctions between these two methods? app.service('reverseService', function() { this.re ...

Limiting the combinations of types in TypeScript

I have a dilemma: type TypeLetter = "TypeA" | "TypeB" type TypeNumber = "Type1" | "Type2" I am trying to restrict the combinations of values from these types. Only "TypeA" and "Type1" can be paired together, and only "TypeB" and "Type2" can be paired tog ...

The object does not have a property named 'fetch' and therefore cannot be read

Struggling to integrate a REST datasource into my Apollo Server. I've created a class that extends RESTDataSource for handling API requests. However, when attempting to call the login method from my GraphQL resolver code, an error is being thrown. An ...

Encountering an unidentified entity within a ReactJS application

Within a container, I've included a search bar inside a form element with two inputs - from and to, along with a submit button. Upon submitting the form, I create an OBJECT named query which looks like this: const query = { from : this.s ...

Refresh a function following modifications to an array (such as exchanging values)

Looking to re-render a function after swapping array values, but the useEffect hook is not triggering it. I need assistance with this as I plan to integrate this code into my main project. Below are the JSX and CSS files attached. In App.js, I am creating ...

Experiencing challenges with accessing a multidimensional array in PHP

Struggling to extract the correct data from this complex array obtained through FirePHP: array( ['day'] => 'Wed' ['is_used'] => 1 [0] => array( ['day'] => 'Wed' ...

Bringing in a Native JavaScript File to Your Vue Component in Vue Js

After developing a frontend application using Vue Js, I encountered the need to integrate a native JavaScript file into one of my Vue components. This native js file contains various utility functions that I would like to access and use within my Vue comp ...

Certain conditions in JavaScript are not executed by Internet Explorer

I am currently working on a Html file that involves XSLT. I have integrated some JavaScript code for filtering specific rows within tables. However, I have encountered an issue where certain if-cases in my JavaScript are not executing as expected when usin ...

Verifying the selection state of a dynamically generated checkbox with JavaScript

I have a table with checkboxes. Each time a button is clicked, I dynamically add new checkboxes to the table like so: var cell3 = row.insertCell(2); cell3.innerHTML = '<input type="checkBox" value=\"selected?\" style="cursor:poin ...

How can I use ReactJS to find the nearest five locations in order from closest to farthest?

I'm in the process of creating a website for searching nearby locations. I am facing an issue where I want to display the 5 closest locations from my current location in ascending order, but I keep getting the same location result. I need these locati ...

When utilizing Vue JS, each key value of one computed property can trigger another computed property to run

I have a computed property: getRelatedItem () { return this.allItems.find((item) => { return item.id === this.currentSelectedItemId }) }, Here is an example of the output: relatedItem:Object -KQ1hiTWoqAU77hiKcBZ:true -KQ1tTqLrtUvGnBTsL-M:tr ...

Developing a jsp page with interconnected drop down menus

I am looking to dynamically populate the options in a second drop-down based on the selection made in the first drop-down. For instance, if I have a first drop-down with options {India, South Africa, USA}, and I choose India, then the second drop-down shou ...

Navigating an array to link values to anchor tags

I'm struggling with an array that contains image file names ["1352.jpg", "1353.jpg", "1354"]. My goal is to loop through this array and generate anchor links for each item separated by commas. I've attempted the following code snippet, but it&apo ...

Angular.js has encountered an error due to exceeding the maximum call stack size

Hello everyone! I attempted to create recursion in order to extend my $routeProvider in Angular.js with the following code: var pages = { 'home': { 'url': '/', 'partialName': 'index', ...

What is the best way to include rxjs in an npm library - as a dependency, peer dependency, or both?

After researching numerous posts and articles on dependencies versus peerDependencies, I am still not entirely certain what to do in my particular situation.... I have a library (which is published to a private npm repository) that utilizes rxjs; for exam ...

Gulp Watch fails to identify changes in the SASS SCSS directory

After setting up Gulp to compile SCSS into CSS using NanoCSS and gulp-css for the first time, I encountered an issue. While my do-sass command successfully compiles SCSS and minifies CSS files, it does not run when placed within a watch task. Any changes ...

What is the best method for comparing the keys and values of two arrays?

I'm facing a challenge with two arrays that have similar keys and values. My goal is to create a new array containing only the values that are not present in the first array. I attempted to use the array_intersect function, but the outcome was unexpec ...

Issues surrounding the determination of CSS attribute value using .css() function within a variable

I have been working on a function to change the color of a span dynamically from black to a randomly selected color from a predefined list. However, I am encountering an issue with the .css("color", variableName) part of my code and suspect that my synta ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...