0

I am trying to make a basic Average Calculator in HTML and JavaScript. I have the input field and buttons in HTML and the averaging and Reset functions in JavaScript. I cannot find where my problem is.

HTML Code:

<section class="script">
  <script src="avg.js"></script>
  <input type="number" id="inputVal" placeholder="Input Value..."></number><br>
  <button id="Btn_Avg" onclick="AddFunc(inputVal.Value)">Average</button>
  <button id="Btn_Rst" onclick="ResetFunc()">Reset</button>
  <p>Average: </p><p id="average">OK</p>
</section>

JavaScript script (avg.js):

global var count = 0;
global var total = 0;
global var avg = 0;
global var result = document.getElementById("average");
result.textContent = 0;

function AddFunc(value){
  total += value;
  count += 1;
  avg = total / count;
  result.innerHTML = '' + avg;
}

function ResetFunc() {
  total = 0;
  count = 0;
  avg = 0;
  result.innerHTML = '0';
}

2 Answers 2

1

Well, for one, it should be inputVal.value (lowercase value). That should correctly pass the input value to your function. But your question doesn't really describe what issue you're running into, so I'm not sure that answers your question.

Also I don't think global is a valid keyword for JavaScript.

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is in this part onclick="AddFunc(inputVal.Value)". This will not pass value of inputVal to the function. You should store the <input> element in a variable and access its value using small vi.e value

var count = 0;
var total = 0;
var avg = 0;
var result = document.getElementById("average");
var input = document.getElementById('inputVal')
result.textContent = 0;

function AddFunc(e){
  let value = Number(input.value);
  total += value;
  count += 1;
  avg = total / count;
  result.innerHTML = '' + avg;
}

function ResetFunc() {
  total = 0;
  count = 0;
  avg = 0;
  result.innerHTML = '0';
}
<input type="number" id="inputVal" placeholder="Input Value..."></number><br>
  <button id="Btn_Avg" onclick="AddFunc(event)">Average</button>
  <button id="Btn_Rst" onclick="ResetFunc()">Reset</button>
  <p>Average: </p><p id="average">OK</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.