Skip to content
Advertisement

How can I use local variable from one function and use them in another function, if this is even possible?

My Problem

I have a function called mathsFormula() which is supposed to calculate the two input fields located in the second function called renderRow() and display that answer in the <div> labelled result.

However, I don’t know how to attach the local variables from renderRow() function so they work inside the mathsFormula().

What is the best solution to solve this problem?

This is the mathsFormula() function

document.addEventListener("keyup", mathsFormula());

function mathsFormula() {

const calculate = (input1.value * input2.value) - input2.value; 
result.textContent = calculate

}

This is the renderRow() function

function renderRow() {
  
  const row = document.createElement('div');

  const label = document.createElement("label");
  
  const input1 = document.createElement("input");
  input1.type = "number";
    
  const input2 = document.createElement("input");
  input2.type = "number";
  
  const result = document.createElement("div");

  row.append(label, input1, input2, result);

Advertisement

Answer

You need to expose these variables by returning them from the function. You can return them in an object, e.g. return { bet_label, input_field, input_div };, so when the function is called it will return an object containing references to these elements.

function addRow(rowNumber) {

  const bet_label = document.createElement("label");
  a.appendChild(bet_label);
  bet_label.classList.add('betLabel');
  bet_label.textContent = "Bet " + rowNumber;

  const input_field = document.createElement("input");
  a.appendChild(input_field);
  input_field.classList.add('oddsEntry');
  input_field.type = "number";

  const input_div = document.createElement("input");
  a.appendChild(input_div);
  input_div.classList.add('stakeEntry');
  input_div.type = "number";

  const result_div = document.createElement("div");
  a.appendChild(result_div)
  result_div.classList.add('resultDiv');
  result_div.textContent = "";

  const btn_Del = document.createElement("button");
  btn_Del.classList.add('deleteBtn');
  btn_Del.innerHTML = '<i class="fa-solid fa-trash"></i>';
  a.appendChild(btn_Del);

  return {
    bet_label,
    input_field,
    input_div,
    result_div,
    btn_Del
  };
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement