Attempting to gather data from an HTML form and perform calculations on it using JavaScript

Looking for help with extracting user input from HTML and performing mathematical operations in JavaScript. Coming from a Python background, the variable system in JavaScript is confusing to me. Can someone provide guidance on how to achieve this?

<div class="text">Enter your energy usage:</div>
<input id="q1" type="text" placeholder="# of Kilowatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<!-- Multiply InputValue by 3 and Add 2 -->

I attempted to use parseInt and parseString but encountered issues as it refused to execute.

Answer №1

Here's a suggestion for you to try out: begin by querying the input value, then calculate your desired numbers and finally notify the user using an alert message, for example

<!-- InputValue multiplied by 4 and then subtracted by 1 —->

function findInputValue() {
  const inputValue = document.getElementById("q2").value; //querying input value
  const calculatedResult = ((inputValue *4) -1);   // initial step: multiply input value by 4
                                                // second step: subtract 1 from the result
 alert(calculatedResult);  // display the calculated result via an alert
};

Answer №2

Give it a go and experiment with the code snippet below. Enjoy!!

<html>
<body>
    <label for="insertValue">Enter Your Value:</label>
    <input type="text" id="insertValue">

    <button onclick="Multiply()">Multiply</button> <!-- Triggering JS function on button click -->
    <p id="answer"></p>

    <!-- Remember to include your JS Scripts before closing the <body> tag -->
    <script>
        function Multiply() {
            let value = document.getElementById("insertValue").value; //retrieve input value from <input> text box
            let answer = 0;

            //Perform Multiplication
            answer = value * 2 * 3;

            //Show the result in the <p> tag with id ="answer"
            document.getElementById("answer").innerText = "Your Answer is: "+ answer;

        }
    </script>
</body>
</html>

Answer №3

Simple Solution:

<div class="content">How much water do you need?</div>
<input id="q1" type="text" placeholder="# of liters"></input>
<button type="button" onclick="calculateWater();">Calculate</button>
<br>
<output id="a1"></output>

<script>
  var input = document.getElementById("q1");
  var output = document.getElementById("a1");

  function calculateWater() {
    output.textContent = (input.value * 2) + 5;
  }
</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

When the child content surpasses the height of the parent, you can scroll within an overflow:visible; div

My sidebar navigation menu includes children and sub-children that are revealed on hover. You can view a simplified version of it in this jsfiddle link: https://jsfiddle.net/s096zfpd/ Although the example provided is basic, my main concern arises when the ...

The screen reader is unable to interpret the text that is visible within the anchor tag

I have an Angular application with a dropdown menu implemented as shown below. When using the NVDA screen reader to navigate, only the content inside the aria-label attribute is being read when tab focused. However, I want it to also read the content (&ap ...

React is struggling to dynamically update text content using button click events

As a beginner in the world of React, Nodejs, and JavaScript, I am exploring onClick events to dynamically change text by clicking buttons. In my practice project, I have an input type="checkbox" that toggles the text between bold and normal style ...

The package.json file is missing the "exports" main, causing the Error [ERR_PACKAGE_PATH_NOT_EXPORTED] to be displayed

Can anyone help me resolve the 'Error [ERR_PACKAGE_PATH_NOT_EXPORTED]: No "exports" main defined in package.json' issue? I've been struggling to fix it despite receiving assistance. The problem is quite baffling and the more I dwel ...

How to Keep Button Highlighted After Clicking

I've experimented with various methods like using :active, :focus, adding a class, and modifying CSS rules through jQuery to maintain the button highlight, but none of them have been successful. Please take a look at my code and point out any mistakes ...

Angular: Design dependent on attributes

Can I customize the styling of a div in accordance with a boolean property called "isActive" on my controller using Angular? <div class="col-md-3" (click)="isActive = !isActive"> <div class="center"> <i class="fa fa-calendar"& ...

Combining Angular and Bootstrap: how to create two overlapping divs

Looking to enhance a project in Angular 15 + bootstrap 5 by creating two draggable divs where the lower one can be vertically resized to overlap the upper one? I've managed to set up most of it, but when dragging the lower div, its transparency makes ...

Is it possible to trigger an ajaxcall once another one has finished executing?

Just curious, do you think the code snippet below is capable of triggering a second ajax function once the first one has completed successfully? if(xmlHttp) // xmlHttp represents an XMLHttpRequest object { xmlHttp.onreadystatechange = function() ...

Develop a map in JavaScript that uses a parent key to filter data from an object and then stores it in the map

con_data = { "0": { "Actual1920": 2379403, "Budget1920": 10121051.161450788, "CostOwner": "Dr. Ratnavat", "LTRevExp": "Expense-EB", "LedgerBudget": "Salary", "LedgereType": "Salary-Teaching", ...

How to import a template from a different webpage in AngularJS

I have a situation where I need to include a template from one HTML page into another because they are both lengthy and it's not practical to keep them on the same page. Therefore, I have decided to separate them for better organization. Here is an ov ...

Rails 6 not displaying Javascript as intended

I am a beginner at this, but so far everything seems to be functioning smoothly. On my page, users can upload and delete photos without any issues. The uploading and deleting processes work perfectly fine. However, I am facing an issue where the page does ...

Webpack2 now transforms sass/scss files into JavaScript rather than CSS during compilation

I've created a webpack script to compile all .scss files into one css file. I decided to use webpack instead of gulp or grunt for simplicity, as it can be configured in a single file. However, I am encountering an issue where scss files are being com ...

Issue encountered when displaying an organized list in next.js

I have been working on rendering an array of items in descending order based on their values. Everything seems to be functioning correctly, but I keep encountering an error that reads Error: Text content does not match server-rendered HTML. whenever I tr ...

Stop processing the current websocket connection once a new websocket request is received

Currently, I am utilizing the npm ws module (or its wrapper named isomorphic-ws) for establishing a websocket connection. NPM Module: isomorphic-ws This setup allows me to retrieve an array of data from a websocket++ server situated on the same local mac ...

Issue with JQuery Ajax form causing unexpected page refresh in Safari but not in Firefox (working properly)

Currently, I am working on an AJAX form that is housed within a JQUERY UI Dialog. Everything runs smoothly in FireFox; however, there seems to be a glitch in Safari as it refreshes the page to: /? If you notice any discrepancies or errors here, please do ...

Allow only specific inner divs to dictate the width of the outer div

I'm working with the following HTML structure: <div id="container"> <div id="block1"> <img src="someimage/path" /> </div> <div id="block2"> Some Text </div> <div id="block3"&g ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

Extracting HTML element from PHP string and placing it in a different page

In a PHP string, there is an HTML structure including a table within it: <html> <head> <!-- not much going on here --> </head> <body> <table border="0" align="center" cellpadding="0" cellspacing="10 ...

Leveraging Ajax and jQuery to create a POST request for adding a new record to a MySQL table within a Node.js server

My form is designed to collect user information like name, age, and more. The aim is to submit this data from the client side, inserting it into a MySQL table row. However, I'm facing difficulties in getting the data to successfully insert. Below are ...

Modal shows full JSON information instead of just a single item

This is a sample of my JSON data. I am looking to showcase the content of the clicked element in a modal window. [{ "id": 1, "companyName": "test", "image": "https://mmelektronik.com.pl/w ...