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">
counter1
counter2
<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>
Two major problems:
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.
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">