DarthBinks911 DarthBinks911 - 4 years ago 111
HTML Question

Dynamic input for number counters in Javascript

I'm trying to create two number counters that can increment and decrement the other counter in real-time. Also I don't know Javascript too well.

<input type="number" step="1" value="10" name="counter1" id="counter1">

<input type="number" step="1" value="10" name="counter2" id="counter2">


If
counter1
is increased,
counter2
should be decreased, and vice versa; they are basically the inverse of each other. I've tried to implement some Javascript but it's not going well and I'm unsure of how to implement both incrementing and decrementing at the same time.

<script type="text/javascript"> //some non-working example code
function count() {
var counter1 = document.getElementById('counter1').value;
var counter2 = document.getElementById('counter2').value;
document.getElementById('counter2').onclick = function() { //onclick doesn't take into account if the input was increased or decreased.
counter2++;
counter1--;
}​
document.getElementById('counter1').onclick = function() {
counter1++;
counter2--;
}​
}
count();
</script>

Answer Source

Two major problems:

  1. Assigning an input's value to a variable does not create a reference, it creates a copy. That means it isn't going to modify the number stored in the input, just the copied variable that you created.

  2. You shouldn't use the click event. You should use the change event since it will fire whenever the value changes.

Finally, you can track the previous value of each input and compare it against the new value to determine if it increased or decreased. Even more simply, you can calculate the difference between those values and subtract that difference from the other inputs value.

var counter1 = document.getElementById('counter1');
var counter2 = document.getElementById('counter2');
var prevCounter1 = counter1.value;
var prevCounter2 = counter2.value;

counter1.addEventListener('change', function() {
  var value1 = parseInt(counter1.value);
  var value2 = parseInt(counter2.value);
  var delta = value1 - prevCounter1;
  counter2.value = value2 - delta;
  prevCounter1 = value1;
});

counter2.addEventListener('change', function() {
  var value1 = parseInt(counter1.value);
  var value2 = parseInt(counter2.value);
  var delta = value2 - prevCounter2;
  counter1.value = value1 - delta;
  prevCounter2 = value2;
});
<input type="number" step="1" value="10" name="counter1" id="counter1">
<input type="number" step="1" value="10" name="counter2" id="counter2">

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download