Retrieve the values of two inputs from outside of the event

How can I access the values of two input fields in order to perform calculations as soon as their values are updated?

<script>
// Accessing the values of the two input fields for immediate calculation based on user input
const heightInputEl = document.querySelector('.height-input');
const weightInputEl = document.querySelector('.weight-input');

heightInputEl.addEventListener('input', function (e) {
  const height = Number(e.target.value);
  const mtrsqr = Math.abs(Math.pow(height / 100, 2));
});

weightInputEl.addEventListener('input', function (e) {
  const weight = Number(e.target.value);
});
</script>


Answer №1

let area
let mass

const heightInputEl = document.querySelector('.height-input');
const weightInputEl = document.querySelector('.weight-input');

heightInputEl.addEventListener('input', () => {
  let height = Number(heightInputEl.value);
  area = Math.abs(Math.pow(height / 100, 2));
});

weightInputEl.addEventListener('input', () => {
  mass = Number(weightInputEl.value);
});

By declaring area and mass outside the event listeners, they can be accessed globally

Answer №2

It seems like your code is not running because it is executing before the HTML elements are fully loaded. A simple fix for this issue is to use setTimeout, which delays the execution until after the page has loaded. Here's an example that demonstrates how you can modify your code to work correctly: https://jsfiddle.net/hiyer/sL18nqe7/36/

<html>

<script>
  // To calculate values immediately when input changes
 setTimeout( function (){
        const heightInputEl = document.querySelector('.height-input');
    const weightInputEl = document.querySelector('.weight-input');
    heightInputEl.addEventListener('input', function (e) {
    const height = Number(e.target.value);
    const mtrsqr = Math.abs(Math.pow(height / 100, 2));
    const mtrsqrEl = document.querySelector('#mtrsqr');
    mtrsqrEl.textContent=""+mtrsqr;
    
      });

   weightInputEl.addEventListener('change', function (e) {
    const weight = Number(e.target.value);
    const weightEL = document.querySelector('#weight');
        weightEL.textContent=weight;   
  });

},100);

</script>
<body>
      Height:<input class="height-input" value="10"/ >
      <br/>
      Weight:<input class="weight-input" value="10">
      <br/>
      Mtrsqr:<label id="mtrsqr"></label>
      <br/>
      Weight:<label id="weight"></label>
      <br/>
</body>


</html>

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

Position the division at the location of the cursor for particular usemap components

Looking for a way to position a division on top of an image using a usemap. Interested in having the div only appear when the mouse hovers over a particular area, and at the precise location of the cursor. Came across some examples using jQuery, similar ...

What is the method for formatting within the <textarea> element?

While working on developing a comment system, I recently made the discovery that text areas cannot be formatted to retain paragraphs, line breaks, etc. This was particularly noticeable when comparing sites like StackOverflow, which uses a text editor inste ...

The response header does not contain a valid JWT token

Here's a function I've implemented to authenticate users by creating a response header: function verifyUser(res, id) { const payload = { id } const token = jwt.sign(payload, config.JWT_KEY, { expiresIn: '24h' ...

Vanishing elements when employing the react-router library in a React project

Currently, I am in the process of developing a React application and have encountered an issue with components disappearing upon refresh. It seems to be related to React Router, suggesting that I may be implementing it incorrectly. This is what my App.js ...

Divide a string into smaller sections beginning at " ] " and concluding with "As"

In Microsoft SQL Server 2008 R2, I have fetched a string from a stored procedure using the query: EXEC sp_helptext 'MyStoredProcedureName';. My task is to divide this string into arrays or substrings that start from the closing parenthesis "]" a ...

Modify Knockout applyBindings to interpret select choices as numeric values

Utilizing Knockout alongside html select / option (check out Fiddle): <select data-bind="value: Width"> <option>10</option> <option>100</option> </select> Upon invoking applyBindings, the options are interprete ...

AngularJS binding variables to HTML tag attributes

Currently, I am going through the tutorials and documentation for Angularjs that is provided on the official Angularjs website. One of the examples involves adding a select box for ordering which looks like this: <select ng-model="orderProp"> ...

The documentation for Gridsome/Netlify CMS has a flaw that results in Graphql not functioning

My attempts to integrate Gridsome with NetlifyCMS using Gridsome's documentation have been unsuccessful. Below is a snippet of the Netlify config.yml setup: collections: - name: "posts" label: "Posts" folder: "posts" create: true s ...

Validating American phone numbers using regular expressions

I came across a Javascript regex that is used to validate the different formats in which US phone numbers can be written. However, there seems to be an issue with it: it fails to match the second rule within this specific group: The first group of three ...

Storing Code into mongoDB with the Help of CasperJS

What is the best way to save data scraped using casperjs into MongoDB? My casperjs script scrapes information from millions of websites and saves each site's content in its own folder. However, I have come to realize that it would be more efficient to ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

Discovering the Cookie in Angular 2 after it's Been Created

My setup includes two Components and one Service: Components: 1: LoginComponent 2: HeaderComponent (Shared) Service: 1: authentication.service Within the LoginComponent, I utilize the authentication.service for authentication. Upon successful authent ...

7 Tips for Renaming Variables in VSCode without Using the Alias `oldName as newName` StrategyWould you like to

When working in VSCode, there is a feature that allows you to modify variables called editor.action.rename, typically activated by pressing F2. However, when dealing with Typescript and Javascript, renaming an imported variable creates aliases. For exampl ...

Tips for maintaining the state in a React class component for the UI while navigating or refreshing the page

Is there a way to persist the selection stored in state even after page navigation? I have heard that using local storage is a possible solution, which is my preferred method. However, I have only found resources for implementing this in functional compone ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

Can you explain the distinction between using get() and valueChanges() in an Angular Firestore query?

Can someone help clarify the distinction between get() and valueChanges() when executing a query in Angular Firestore? Are there specific advantages or disadvantages to consider, such as differences in reads or costs? ...

What is the best way to add a filter to a nested array?

I am currently facing a challenge in creating a multiple filter for multiple arrays without duplicating the nested array. I am working with vuejs and some plugins that are relying on the array, so my only option is to filter it without modifying it. Using ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

I'm looking for a way to convert an array value to JSON using jQuery

i need assistance in converting an array value into json format. An example is provided below: Sample Array [Management Portal!@!@Production Issue Handling!@!@/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!@!@ Event Browser!@!@/ION ...

Uploading a file to a URL using Node.js

Looking for a way to replicate the functionality of wget --post-file=foo.xpi http://localhost:8888/ in nodejs, while ensuring it's compatible across different platforms. In need of assistance to find a simple method for posting a zip file to a specif ...