Jimmy
Jimmy

Reputation: 61

JavaScript: How to calculate and update input field value based on inserted value from the other

I have two input fields and a variable:

var x = 5;

First: <input type="text" name="first">
Second: <input type="text" name="second">

When I input a value in the first input field I want to update and display the second input field value with: first-input-field-value * x

When I input a value in the second input field I want to update and display the first input field value with: x / second-input-field-value

Upvotes: 3

Views: 1373

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30360

A simple solution would be to implement event handlers that perform the respective arithmetic for each input element. Some things to consider would be:

  • ensuring the user supplied input is a valid number. Below I parse the current string value of the updated input and ensure the parsed result is a valid number before performing the arthimetic
  • use the input event ensure that arthimetic and input updates are peformed immediatly, and for different user interactions (keypress, paste from keyboard, etc)

In code this can be written as:

/* Query document for first and second input elements */
const inputFirst = document.querySelector('input[name="first"]');
const inputSecond = document.querySelector('input[name="second"]');

const x = 5;

/* 
Add event handler for the input event that will be run when user interaction 
with input causes value change 
*/
inputFirst.addEventListener("input", (event) => {

  /* Obtain current numeric value for this input after user interaction */
  const value = Number.parseFloat(event.target.value);

  if(!Number.isNaN(value)) {
     /* 
     The value is a number, so we're safe to use it for arithmetic. Here
     we update the value of the secondInput from the input event of the
     firstInput 
     */
     inputSecond.value = value * x;
  }
  
});

inputSecond.addEventListener("input", (event) => {
  
  const value = Number.parseFloat(event.target.value);

  if(!Number.isNaN(value)) {
     inputFirst.value = value / x;
  }
  
});
First: <input type="text" name="first">
Second: <input type="text" name="second">

Upvotes: 3

Related Questions