dimanche 3 octobre 2021

trying to link checkbox list with multiple functions using HTML & JAVASCRIPT

my code calculates the AVG or MAX of an input set of numbers, I want the user to check on a checkbox list that contains AVG and MAX for desired output but I couldn't figure out doing it.

if I put an input of "2,4" without check listing the output is both AVG and MAX which is 3 4, I tried to checklist for only AVG or MAX outcome but it didn't work.

I have checked both function calculateAVG() & calculateMAX() and they produce correct output

function proccesFloat(flt) {
  var splitFloat = flt.split(",");
  for (x in splitFloat) {
    splitFloat[x] = parseFloat(splitFloat[x]);
  }
  return splitFloat;
}

function calculateAVG(setNum) {

  let total = 0;
  var numInput = document.getElementById("setNum").value;
  var result = 0;
  var avg = proccesFloat(numInput);

  for (let i = 0; i < avg.length; i++) {
    total += avg[i];
  }
  result = total / avg.length;
  document.getElementById('outputAVG').innerHTML = result;

}

function calculateMAX(setNum) {

  var numInput = document.getElementById("setNum").value;
  var numarry = proccesFloat(numInput);
  var max = 0;
  for (let i = 0; i < numarry.length; i++) {
    if (numarry[i] > max) {
      max = numarry[i];
    }
  }
  document.getElementById('outputMAX').innerHTML = max;
}

function calculate() {
  var checkBox = document.getElementsByTagName("check");


  if (checkBox[0].checked) {
    calculateAVG(document.getElementById("setNum"));
  }
  if (checkBox[0].checked) {
    calculateMAX(document.getElementById("setNum"));
  } {
    alert('please choose formula')
    return false;
  }
}
<header>

  <input type="Numbers" id="setNum" placeholder="Enter Set of Numbers">
  <br>
  <button onclick="calculate()" id="btn1">calculate</button>
  <output id="outputAVG"></output>
  <output id="outputMAX"></output>

  <form method="post">
    <fieldset>
      <legend>Formula To Calculate?</legend>
      <input type="checkbox" id="avg" name="check" onclick="calculate()">AVG<br>
      <input type="checkbox" id="max" name="check" onclick="calculate()">MAX<br>
      <br>

    </fieldset>
  </form>
</header>



Aucun commentaire:

Enregistrer un commentaire