Home > Software engineering >  How to change global variable with button value onclick
How to change global variable with button value onclick

Time:10-27

I am making a simple calculator using html and Javascript. Here is the code that is working and updating the calculator display when the button is clicked.

const display = document.querySelector('#display');

const cells = document.querySelectorAll('.cell');
cells.forEach((cell) => {
    cell.addEventListener('click', (e) => {
        if (e.target.value !== NaN) {
            a = e.target.value;
        } else {
            a = parseInt(e.target.value, 10);
        };
        display.textContent  = a   ' ';
    });
});

I am trying to save the button value into a global variable so I can use it later in math operations as shown below. I declared a global variable x and tried to update it when the buttons are clicked.

const display = document.querySelector('#display');

let x;

const cells = document.querySelectorAll('.cell');
cells.forEach((cell) => {
    cell.addEventListener('click', (e) => {
        if (e.target.value !== NaN) {
            a = e.target.value;
            x = a;
        } else {
            a = parseInt(e.target.value, 10);
            x = a;
        };
        display.textContent  = a   ' ';
    });
});

console.log(x);

The display.textContent is working as intended but console.log(x) isn't updating when the buttons are clicked. How do I update the variable x with button.value?

CodePudding user response:

You are accessing the variable before the value is assigned to it.

onClick function will be called when user click on the ".cell" element

const display = document.getElementById('#display');

let x;

const cells = document.querySelectorAll('.cell');
cells.forEach((cell) => {
    cell.addEventListener('click', (e) => {
        if (e.target.value !== NaN) {
            a = e.target.value;
            x = a;
        } else {
            a = parseInt(e.target.value, 10);
            x = a;
        };
        display.textContent  = a   ' ';
    });
});


// Called first
console.log(x);

// Asyn call
setInterval(function(){
  console.log("from Interval");
  console.log(x);
}, 1000)
input {
  display: block;
}
<div id="#display"></div>
<input class="cell" value="1"/>
<input class="cell" value="2"/>
<input class="cell" value="3"/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Apart from not showing x outside of where you set it, I strongly suggest you delegate

const getNum = n => !isNaN(parseFloat(n)) && isFinite(n) ? parseInt(n) : 0;
window.addEventListener("load", function() { // on page load
  const calc = document.getElementById('calc');
  const display = document.getElementById('#display');
  let x;

  calc.addEventListener('click', (e) => {
    const tgt = e.target; 
    if (tgt.classList.contains("cell")) {
      x = getNum(tgt.value)
      display.textContent  = x   ' ';
      console.log(x);
    }
  });
});
input {
  display: block;
}
<div id="#display"></div>
<div id="calc">
  <input class="cell" value="1" />
  <input class="cell" value="2" />
  <input class="cell" value="3" />
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related