Saving the value in a global variable created outside the scope of the function

0
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width-device-width, initial-scale=1.0">
  <link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">  
 <script>
  function calculoMedia()
  {
     var media;
     var b1 = parseInt(document.getElementById('b1').value);
     var b2 = parseInt(document.getElementById('b2').value);
     media = (b1 + b2 * 2) / 3;
     if (media<60){alert("Precisa Recuperar")}else{"Aprovado"}
     alert("Grau Final: " + media + "")
     ;
  }

  </script>
  <title>Médias</title>
</head>
<body>
 <h1 style="text-align:center" style="font-size:arial black">VERIFIQUE SEU GRAU</h1>
  <form>
   <div class="form-group caixa-pesquisa-div text-center">
    <br>1° BIMESTRE:<br><input type="number" id="b1">
    <br>2° BIMESTRE:<br><input type="number" id="b2">
    <br>
    <input type="button" class="btn btn-info" onclick="javascript:calculoMedia();" value="CALCULAR">
   </div>
  </form>
</body>
</html>
    
asked by anonymous 05.12.2018 / 00:06

1 answer

0

You can declare the variable media globally or outside the scope of functions on the page , to be well didactic and reuse it elsewhere in the script and even other scripts. A good documentation for you to better understand about the scope of variables in Javascript is this here .

var media;                                // aqui você declara a variável globalmente

function calculoMedia() {

  var b1 = parseInt(document.getElementById('b1').value);
  var b2 = parseInt(document.getElementById('b2').value);
  media = (b1 + b2 * 2) / 3;
  if (media < 60) {
    alert("Precisa Recuperar")
  } else {
    alert("Aprovado")
  }
  alert("Grau Final: " + media + "");
}

var botao = document.getElementsByTagName('button')[0];
var teste = document.getElementsByTagName('b')[0];

  botao.onclick = function() { 
    teste.innerHTML = media;       // utiliza a variavel já com o valor da função CalculoMedia() 
  }
<h1 style="text-align:center" style="font-size:arial black">VERIFIQUE SEU GRAU</h1>

<form>
  <div class="form-group caixa-pesquisa-div text-center">
    <br>1° BIMESTRE:<br><input type="number" id="b1">
    <br>2° BIMESTRE:<br><input type="number" id="b2">
    <br>
    <input type="button" class="btn btn-info" onclick="calculoMedia();" value="CALCULAR">
  </div>
</form>
<br><br>
<button>Mostrar resultado</button><br>
<b></b>
    
05.12.2018 / 12:59