Wim Mertens
Wim Mertens

Reputation: 1790

Do calculation of new value of changed input

I've got 2 inputs whereby I'd like to calculate weekly to fortnightly and vice versa. So on change I'd like the NEW value to be calculated. I'm not getting the right values though (change weekly needs the value of fortnightly to be multiplied by two and change fortnightly needs the value of weekly divided by two and it only fires once (needs to update after every change).

HTML:

<div class="frequencies">
<div>
   Weekly<br />
  <input class="weekly" type="text" value="1000" />
</div>

  <br /><br />
  <div>
    Fortnightly<br />
    <input class="fortnightly" type="text" value="2000" />
  </div>

</div>

Jquery:

var weekly = $("input.weekly").val(),
    fortnightly = $("input.fortnightly").val();

w2f = parseFloat(weekly, 10) * 2;
f2w = parseFloat(fortnightly, 10) / 2;

$("input.weekly").on("change paste", function() {
  $(this).closest('.frequencies').find('input.fortnightly').val(w2f);
});

$("input.fortnightly").on("change paste", function () {
  $(this).closest('.frequencies').find('input.weekly').val(f2w);
});

Here's a fiddle of the code: https://jsfiddle.net/nh12du38/3/

This should be a simple thing but I'm not seeing it. What am I doing wrong?

Upvotes: 2

Views: 54

Answers (1)

kind user
kind user

Reputation: 41893

You have to be aware that if you assign a value to a variable outside the function inside the listener, it's value will be set only once, on script load and will remain in that state.

You have to move the logic inside every listener, so in case if the change or paste events have taken place, the variables will load a fresh, actual value.

$("input.weekly").on("change paste", function() {
  w2f = parseFloat($("input.weekly").val(), 10) * 2;
  f2w = parseFloat($("input.fortnightly").val(), 10) / 2;
  $(this).parent().parent().find('input.fortnightly').val(w2f);
});

$("input.fortnightly").on("change paste", function() {
  w2f = parseFloat($("input.weekly").val(), 10) * 2;
  f2w = parseFloat($("input.fortnightly").val(), 10) / 2;
  $(this).parent().parent().find('input.weekly').val(f2w);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="frequencies">
  <div>
    Weekly
    <br />
    <input class="weekly" type="text" value="1000" />
  </div>

  <br />
  <br />
  <div>
    Fortnightly
    <br />
    <input class="fortnightly" type="text" value="2000" />
  </div>

</div>

Upvotes: 1

Related Questions