user9362078
user9362078

Reputation: 11

Change input value based on another input's value and vice versa in Javascript

I need help with java script code for changing the value of one input field from another input field and vice versa.

I am building a calculator similar to the Zillow Mortgage Calculator and when you input the down payment %, the down payment dollar amount updates, and it works vice versa, if you input the dollar amount the percentage field updates.

zillow calculator link: https://www.zillow.com/mortgage-calculator/

here is the Javascript code I am using and it only works one way not the other. thank you for any help.

<input type="text" id="fname" onchange="myFunction()">
<br><br>
<input type="text" id="james" onchange="myFunction()">


<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value;

var y = document.getElementById("james");
y.value = x.value;

}
</script>

Upvotes: 1

Views: 6703

Answers (3)

Ele
Ele

Reputation: 33726

Just bind the input event to both input fields.

  • Execute getElementById function only once to improve performance.

var fname = document.getElementById('fname');
var james = document.getElementById('james');

fname.addEventListener('input', function() {
  james.value = this.value;
});

james.addEventListener('input', function() {
  fname.value = this.value;
});
<input type="text" id="fname">
<br><br>
<input type="text" id="james">

Upvotes: 2

Obsidian Age
Obsidian Age

Reputation: 42304

The problem is that you're never setting the value of x to be equal to the value of y. And even if you were to do this, considering you're calling the same function both times, the value would immediately get overwritten.

What you want to do is make use of two separate functions that update one another.

Note that you're probably also looking to trigger the function on input rather on change.

Finally, you'll want to extrapolate the logic, and make use of addEventListener():

document.getElementById("fname").addEventListener("input", function(){
    document.getElementById("james").value = this.value;
});

document.getElementById("james").addEventListener("input", function(){
    document.getElementById("fname").value = this.value;
});
<input type="text" id="fname">
<br><br>
<input type="text" id="james">

Upvotes: 3

Jonas Wilms
Jonas Wilms

Reputation: 138267

You actually need to detect a change:

 var prev;

 function updateCalculator() {
    var x = document.getElementById("fname");
    var y = document.getElementById("james");
    if(x.value != prev){
      prev = y.value = x.value;
    } 
    if(y.value != prev){
      prev = x.value = y.value;
    }           
 }

Upvotes: 0

Related Questions