Click to solve the equation

I want to build a basic HTML page with three input variables (A,B,C). After the user inputs these values, they will click "calculate", and JavaScript will execute the following equations:

((A + B)/2) * 3 = X 

and

(C * 2) = Y

The results will be displayed as outputs of X Value and Y Value. Here is an image:

https://i.sstatic.net/E40kS.png

I've set up the HTML but am struggling with the JavaScript. Would appreciate any help :) Thank you in advance!

<!DOCTYPE html>
<html >
<head>
  <meta charset="UTF-8">
  <title>Example</title>;
  
</head>;

<body>

<body class="container">
  <div class="row">
    <div class="span6">
    <h1 align="center">Example</h1>
<form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
  
  <div class="control-group">
    <label class="control-label">A</label>
    <div class="controls">
      <input type="text"  name="A" class="ratecalcfield"></input>
    </div>
</div>
                    <div class="control-group">
                        <label class="control-label">B</label>
                        <div class="controls">
                            <input type="text"  name="B" class="ratecalcfield"></input>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">C</label>
                        <div class="controls">
                            <input type="text"   name="C" class="ratecalcfield"></input>
                        </div>
                    </div>



                    <div class="control-group">
                        <label class="control-label">X Value</label>
                        <div class="controls">
                            <input type="text" name="x" class="ratecalcfield"></input>
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Y Value</label>
                        <div class="controls">
                            <input type="text" name="y" class="ratecalcfield"></input>
                        </div>
                    </div>
                    <div class="control-group w3-margin-top">
                        <div class="controls">
                        <input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc"></input>
                    </div>;
                   
                </div>;
            </form>;
  


    <script src="js/index.js"></script>;

</body>;
</html>

    function cmdCalc_Click() {
            calculate();
    }

    function calculate() {
        A = parseInt(document.getElementById("A").value);
        B = parseInt(document.getElementById("B").value);
        C = parseInt(document.getElementById("C").value);
        
        x = document.getElementById("x");
        y = document.getElementById("y");
        
    x.innerHTML = (3 * C);
    y.innerHTML = (((A + B) / 2 ) * 2));
    }

Answer №1

Take a look here.

I have assigned a unique id to each input element. Then, using JavaScript, I retrieved the elements using document.getElementById. Each element has a property called value which contains the value of the respective input element. When the user clicks on the button, I retrieve the values of A, B, and C, perform calculations, and then set the results to X and Y.

var a = document.getElementById('A');
var b = document.getElementById('B');
var c = document.getElementById('C');
var x = document.getElementById('X');
var y = document.getElementById('Y');

function cmdCalc_Click(){
   x.value = ((Number.parseInt(a.value) + Number.parseInt(b.value)) / 2) * 3
   y.value = c.value * 2;
}
<form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
  
   <div class="control-group">
     <label class="control-label">A</label>
     <div class="controls">
         <input id="A" type="text"  name="A" class="ratecalcfield">
     </div>
   </div>
   
   <div class="control-group">
      <label class="control-label">B</label>
      <div class="controls">
         <input id="B" type="text"  name="B" class="ratecalcfield">
      </div>
   </div>
   
   <div class="control-group">
       <label class="control-label">C</label>
       <div class="controls">
          <input id="C" type="text"   name="C" class="ratecalcfield">
       </div>
   </div>

   <div class="control-group">
        <label class="control-label">X Value</label>
        <div class="controls">
            <input id="X" type="text" name="x" class="ratecalcfield">
        </div>
    </div>
    
    <div class="control-group">
         <label class="control-label">Y Value</label>
         <div class="controls">
             <input id="Y" type="text" name="y" class="ratecalcfield">
         </div>
    </div>
    
    <div class="control-group w3-margin-top">
        <div class="controls">
            <input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc">
         </div>                 
    </div>
</form>

Answer №2

Using the field name instead of "id" in the variable fields is more efficient. You can easily access them by using getElementsByName('inputNameHere')[0].value)

function cmdCalc_Click(){
        var a = Number.parseInt(document.getElementsByName('A')[0].value);
        var b = Number.parseInt(document.getElementsByName('B')[0].value);
        var c = Number.parseInt(document.getElementsByName('C')[0].value);
        var x = Number.parseInt(document.getElementsByName('X')[0].value);
        var y = Number.parseInt(document.getElementsByName('Y')[0].value);

    e1 = ((a + b)/2) * 3
    if(e1 == x && x != 0){
        alert("Great job! " + e1 + " equals " + x);
    }

    e2 = (c * 2)
    if(e2 == y && y != 0){
        alert("Awesome! " + e2 + " equals " + y);
    }
}

Answer №3

all HTML errors have been corrected.

forces inputs to only accept numbers (eliminates unnecessary parseInt in JavaScript).

assign a class for functionality.

perform the calculation.

update x and y values accordingly.

<!DOCTYPE html>
<html >
    <head>
        <meta charset="UTF-8">
        <title>Example</title>
    </head>
    <body>
        <div class="container">
            <div class="row">
                <div class="span6">
                    <form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">
                        <div class="control-group">
                            <label class="control-label">A</label>
                            <div class="controls">
                                <input type="number" id="A" class="ratecalcfield">
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">B</label>
                            <div class="controls">
                                <input type="number"  id="B" class="ratecalcfield">
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">C</label>
                            <div class="controls">
                                <input type="number" id="C" class="ratecalcfield">
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">X Value</label>
                            <div class="controls">
                                <input type="number"  id="x" class="ratecalcfield">
                            </div>
                        </div>
                        <div class="control-group">
                            <label class="control-label">Y Value</label>
                            <div class="controls">
                                <input type="number"  id="y" class="ratecalcfield">
                            </div>
                        </div>
                        <div class="control-group w3-margin-top">
                            <div class="controls">
                                <input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="cmdCalc_Click()" value="Calculate" name="cmdCalc">
                            </div>               
                    </form> 
                </div> 
            </div>   
        </div>
    </body>
    <script>
        function cmdCalc_Click() {
            let x = document.getElementById("x");
            let y = document.getElementById("y");
            const Preset = new calculateValues(x, y);
            const result = Preset.calculate();
            x.value = result.x;
            y.value = result.y;
        }
        class calculateValues {
            constructor(x, y) {
                this.A = (document.getElementById("A").value);
                this.B = (document.getElementById("B").value);
                this.C = (document.getElementById("C").value);
            }
            calculate() {
                return {
                    x: (3 * this.C),
                    y: (((this.A + this.B) / 2) * 2)
                }
            }
        }
    </script>
</body>
</html>

Answer №4

To perform calculations on any expression, you can utilize the JavaScript eval function.

function calculateValues() {
    var num1 = document.querySelector('[name=num1]').value;
    var num2 = document.querySelector('[name=num2]').value;
    var num3 = document.querySelector('[name=num3]').value;
    var result1 = document.querySelector('[name=result1]');
    var result2 = document.querySelector('[name=result2]');

    result1.value = eval("((" + num1 + " + " + num2 + ")/2) * 3");
    result2.value = eval("(" + num3 + " * 2)");
}
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Calculator Example</title>
    </head>

    <body class="container">
        <div class="row">
            <div class="span6">
                <h1 align="center">Simple Calculator</h1>
                <form class="form-horizontal well w3-center" style="max-width: 850px; width: 100%; margin: 0 auto;">

                    <div class="control-group">
                        <label class="control-label">Number 1</label>
                        <div class="controls">
                            <input type="text" name="num1" class="calc-field">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Number 2</label>
                        <div class="controls">
                            <input type="text" name="num2" class="calc-field">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Number 3</label>
                        <div class="controls">
                            <input type="text" name="num3" class="calc-field">
                        </div>
                    </div>

                    <div class="control-group">
                        <label class="control-label">Result 1</label>
                        <div class="controls">
                            <input type="text" name="result1" class="calc-field">
                        </div>
                    </div>
                    <div class="control-group">
                        <label class="control-label">Result 2</label>
                        <div class="controls">
                            <input type="text" name="result2" class="calc-field">
                        </div>
                    </div>
                    <div class="control-group w3-margin-top">
                        <div class="controls">
                            <input type="button" class="w3-button w3-blue w3-padding-large" style="max-width: 200px; width: 100%;" onclick="calculateValues()" value="Calculate" name="calculateBtn">
                        </div>

                    </div>
                </form>
            </div>
        </div>
    </body>
</html>

Answer №5

Your code is facing an issue due to the absence of A, B, C, X, and Y Ids in each form field and the use of innerHTML to set form values for X and Y. X & Y should be text fields and their values need to be set as

X.value=(3*C);
Y.value=((A+B)/2);

Assign the appropriate ids to the text fields that you are referencing in javascript like:

<input type="text" id="A" name="A" class="">

Moreover:

Avoid using value to set the value of a textfield, instead of innerHTML

Additionally, update your onclick event with the following code to prevent submission and page reload:

onclick="cmdCal_Click(); return false"

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

Unlocking the power of dynamic stacking and unstacking in bar charts using chart.js

Looking to customize a barchart to toggle between stacked bars and bars behind each other? Keep in mind that the x-axes should be stacked behind each other. useEffect(() => { if (!myChart) return; if (barStack) { ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

Issues with Monospace Google Fonts on JSFiddle are preventing them from displaying correctly

It's strange how monospace fonts from Google Fonts don't display properly on JSFiddle. Only sans-serif and serif fonts seem to be functioning correctly. ...

The stylish overflow feature in CSS

After reviewing various CSS templates, I noticed that some classes contain the overflow:hidden property without a defined size. As far as I understand, block elements typically expand to accommodate their content unless instructed otherwise. Given this, ...

Leveraging the content delivery network for react-select in a react.js project

I'm having trouble using react-select with cdn. I attempted to download the cdn for react-select but keep encountering an error stating that 'select is not defined'. I also tried downloading the zip package for react-select, but I am unsure ...

The mysterious attribute of "undefined" in React (Redux)

I encountered an issue with an undefined property while attempting to add a product to the cart in React with Redux. It's puzzling because I have a similar action for adding to Favorites that works without any errors. The specific error message points ...

Every Other Element

I'm currently stuck on a math problem and could use some help. The task is to write a JavaScript function that identifies elements at even positions in an array. The array is composed of number elements. The desired result should be displayed in an el ...

Embed message from a Discord Bot

Is it possible to include an image of a bot on the right side of the embedded message? if (message.includes('help')) { msg.channel.send({ embed: { title: "xxxxxx", color: 3447003, description:"Enter **agjgj** to know ...

Angular component communication issue - emitter malfunctioning

Angular 4 Event emitter not functioning as expected despite following a tutorial for implementation. I am open to alternative solutions if available. Here is the code snippet for the transmitter component: .HTML <nav class="navbar navbar-toggleable-m ...

Utilizing Filters in AngularJS to Group and Display Data

I am working with the following object and need to create a filter to group data by ParentCategoryID. [ {id : 116, Desciption : 'Item1', ParentID : 1, parent : 'Parent1'}, {id : 117, Desciption : 'Item2', ParentID : 2, parent ...

A clever way to transfer data between HTML and Java classes

I have recently built a HTML form with multiple fields for adding new items to a list. Here is a snippet of the code: <form v-on:submit.prevent="addItem" class="mt-3"> <div class="container"> <div class="input-field"> <div ...

Modifying Bootstrap 5 color themes does not affect the button color classes

After following the steps outlined in this guide, I successfully customized the default colors of Bootstrap 5 in my React application created using create-react-app. Within my /src/scss/custom.scss file, I can easily utilize any newly defined variables and ...

A wireframe in three.js displaying shapes with invisible edges as dashed lines

I'm undertaking a project to develop a specific type of 3D object using three.js. My goal is to have a cube displayed in wireframe mode with only the edges visible. However, I would like the edges that are positioned behind the cube to appear dashed. ...

Basic Ajax script fails to function properly

I'm having trouble with the external website that is supposed to output valid JSON data. The code seems too simple for there to be an issue, I've tried using both get and post methods. $(document).ready(function() { $.get("https://www.w3scho ...

Approach for importing a .json file from a public folder into a react component

I am currently attempting to compute the array and display the number on the dashboard. I attempted to utilize fetch('data/users.json), but encountered an error indicating 0. I need to calculate the id from two JSON files located in the public folder ...

Error message occurs when creating a pie chart with invalid values for the <path> element in Plottable/D3.js

For those who need the code snippets, you can find them for download here: index.html <!doctype html> <html> <head> <meta charset="UTF-8"> <!-- CSS placement for legend and fold change --> </head> <body ...

Copy the style of a chosen element and apply it to another element

One of the challenges I'm facing involves a dynamic span element that changes based on color selection: <span class="color checked" style="background-color: #ff0000">Red</span> In addition, I have an image element wit ...

Using Javascript to dynamically add form fields based on the selection made in a combo box

I am in the process of creating an information submission page for a website, where various fields will need to be dynamically generated based on the selection made in a combo box. For example, if the user selects "2" from the combo box, then two addition ...

Nested setInterval in JavaScript refers to the practice of nesting

I am attempting to create nested timed code using setInterval. However, my initial approach does not produce any response from Chrome and Firefox: setInterval(function() { console.log('1'); setInterval(function(){ console.log(& ...