+ 1
How do I reuse this function?
I have a more complex site, but the code bit copied here should be representative. Basically, I want to run a simple addition function from 1 button, but for 2 input fields. Because of how the site is supposed to work, both of the fields are identical, but the variables from field 1 are "var1" and those from field 2 are all "var2". So, what I want is a single button to run one function, but get 2 different outputs based on what is in field 1 and field 2. I want to reuse the function, but I can't figure out how to just sub out the numbers for each variable. https://sololearn.com/compiler-playground/W7TFgioQivgT/?ref=app https://sololearn.com/compiler-playground/W7TFgioQivgT/?ref=app
8 odpowiedzi
+ 1
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div>
<input type="number" id="fight1"><br>
<input type="number" id="flee1"><br>
<input type="number" id="freeze1"><br>
<input type="number" id="fawn1">
<p id="output">Output:</p>
</div><br>
<div>
<input type="number" id="fight2" value=2><br>
<input type="number" id="flee2" value=2><br>
<input type="number" id="freeze2" value=2><br>
<input type="number" id="fawn2" value=2>
<p id="output2">Output:</p>
</div><br>
<button onclick="calc()">Calculate</button>
<script>
function calc(){
let sum1 = (+fight1.value) + (+flee1.value) +
(+freeze1.value) + (+fawn1.value);
output.innerText = "0utput: " + sum1;
//console.log(sum1);
let sum2 = (+fight2.value) + (+flee2.value) +
(+freeze2.value) + (+fawn2.value);
output2.innerText = "Output: " + sum2;
//console.log(sum2);
}
</script>
</body>
</html>
+ 1
I interpreted the question as using one function to do two calculations.
I used several shortcuts here:
(+input.value) shortcut for number conversion
directly referencing the id in js to bypass the getElementById call.
I also restyled the html.
0
i'm not quite clear on what you are wanting to do... your code bit has 8 input fields, and only adds 4 of the fields up but your question only speaks about 2 input fields. also there is no "var1" or "var2" in your code bit...
0
copy pasteXD
0
Bob_Li thanks for your answer. You've helped with a couple things.
I don't think I asked the question i was trying to ask though, so I'm gonna try again.
0
Aarvyan that's what I'm trying to avoid to keep my code from bloating. I'll ask the question better
0
Mark Niles It sounds like you want to be able to click the button and display the sum of the first div of input values and then click the button again and display the sum of the second div of input values. Is this the case.
0
ODLNT no, I didn't create the example code properly to explain what I'm looking for. I'm going to update the example code and reask the question better