3

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

1
  • There are two events you can look at, a key down event and a change event. What you need to do is add an id to those inputs, and then use js to select them and add an event listener to both (I would use a key down event). Inside that function, update the value of the other input. Commented Aug 28, 2019 at 23:55

1 Answer 1

3

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">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.