How to save the value in a global variable created outside the function scope

Asked

Viewed 118 times

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>
  • 1

    Amanda, use the question editor to explain the question better. Just putting a title and a lot of code is not the most suitable to search for a solution. For example, vc did not say which is the variable.

  • Possible duplicate: https://answall.com/questions/32251/varivel-global-em-javascript

1 answer

0

You can declare the variable media globally ie outside the scope of existing functions on the page, to be well taught and reuse it in any other script location and even other scripts. A good documentation for you to better understand about the scope of Javascript variables 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.