Home > Mobile >  reuse function with different variables
reuse function with different variables

Time:01-21

I want to reuse my functions without having to copy-paste the same code

so I want the user to input a value

click a button to call the function and calculate a result

then enter another value and click a different button to call the function and calculate a result

as shown below

function CalcPG() {

  var depth, time, pg;

  depth = Number(document.getElementById("dive1depth").value);
  time = Number(document.getElementById("dive1time").value);

  sum = depth   time;

  prod = depth * time

  document.getElementById("sum").value = sum;
  document.getElementById("prod").value = prod;
}
<h1>Calculation 1</h1>

<label>Enter depth:</label>
<input id="dive1depth" type="number" placeholder="depth"><br>

<br>

<label>Enter time:</label>
<input id="dive1time" type="number" placeholder="time"><br>

<br>

<button onclick="CalcPG()">Calculate Pressure Group</button>

<p>The Sum is: <output id="sum" size="40"></output></p>
<p>The Product is: <output id="prod" size="40"></output></p>

<!-- BREAK -->

<h1>Calculation 2</h1>

<label>Enter depth:</label>
<input id="dive2depth" type="number" placeholder="depth"><br>

<br>

<label>Enter time:</label>
<input id="dive2time" type="number" placeholder="time"><br>

<br>

<button onclick="CalcPG()">Calculate Pressure Group</button>

<p>The Sum is: <output id="sum2" size="40"></output></p>
<p>The Product is: <output id="prod2" size="40"></output></p>

CodePudding user response:

I am also a noob in javascript, so take this with a grain of salt. Firstly i would change the calcPG function

change the function function CalcPG(x) to take a x argument ( x = 1 , x =2 and so on...)

depth = Number(document.getElementById(`dive${x}depth`).value);  
time  = Number(document.getElementById(`dive${x}time`).value);   

document.getElementById(`sum${x}`).value = sum;  
document.getElementById(`prod${x}`).value = prod;

adding `` and ${ } so that if you call CalcPG(1) you get for example "div1depth"

And making some changes on HTML

    <button onclick="CalcPG(1)">Calculate Pressure Group</button>
    <p>The Sum is: <output id="sum1" size="40"></output></p>
    <p>The Product is: <output id="prod1" size="40"></output></p>


    <button onclick="CalcPG(2)">Calculate Pressure Group</button>
    <p>The Sum is: <output id="sum2" size="40"></output></p>
    <p>The Product is: <output id="prod2" size="40"></output></p>
   
  •  Tags:  
  • Related