I have two input fields that each trigger a function when their content changes.
document.getElementsByName("playerOut")[0].addEventListener('change', swapPlayerOut);
document.getElementsByName("playerIn")[0].addEventListener('change', swapPlayerIn);
Each of those two functions dynamically update innerHTML content based on the input.
// Swaps out the player being sold
function swapPlayerOut() {
var om = document.getElementsByClassName("outMil")[0];
var result = entries.find(player => player.gsx$playerfullname.$t === this.value);
om.innerHTML = result.gsx$value.$t;
a = result.gsx$value.$t;
};
// Swaps in the player being bought
function swapPlayerIn() {
var im = document.getElementsByClassName("inMil")[0];
var result = entries.find(player => player.gsx$playerfullname.$t === this.value);
im.innerHTML = result.gsx$value.$t;
b = result.gsx$value.$t;
};
And the HTML:
<div class="grid-container-transfers">
<div class="outMil"></div>
<div class="inMil"></div>
<div class="PandL"></div>
</div>
I need to update the third HTML element <div class="PandL">
with a calculation of a
and b
that are being passed outside of their local functions.
I've got it working with two more event listeners:
document.getElementsByName("playerOut")[0].addEventListener('change', pl);
document.getElementsByName("playerIn")[0].addEventListener('change', pl2);
calling two more functions:
function pl () {
var pandl = document.getElementsByClassName("PandL")[0];
pandl.innerHTML = -a;
}
function pl2 () {
var pandl = document.getElementsByClassName("PandL")[0];
var round = a-b;
pandl.innerHTML = round.toFixed(1);
}
But this feels MIGHTY ineffecient and unstable, so I'm wondering if anyone knows of a more efficient way of achieving the calculation of a-b
.
I'm still quite new to js, and I'm sure this is 101 stuff, but if anyone knows how to do this, I'd be grateful. Cheers!