0
In this code I am testing for the user to put two notes and the JS run the calculation and print on the screen for the user to see. However, I’m not being able to make the average result appear on the screen, but I’m managing to make it appear as a warning. Could you help me?
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
<title>Hello, world!</title>
<style>
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1>Sistema de Aprovação/Reprovação</h1>
<div class="container">
<form>
<div class="form-group">
<label for="exampleInputEmail1">Digite a primeira nota</label>
<input type="number" class="form-control" id="nota1">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Digite a segunda nota</label>
<input type="number" class="form-control" id="nota2">
</div>
<div class="form-group form-check">
</div>
<button onclick="CalculaMedia()" type="submit" class="btn btn-primary">Calcular a Média</button>
</form>
<div id='res'>A média do aluno é:</div>
</div>
<script>
function CalculaMedia() {
var tn1 = document.getElementById('nota1');
var tn2 = document.getElementById('nota2');
var res = document.getElementById('res');
var n1 = Number(tn1.value);
var n2 = Number(tn2.value);
var m = (n1 + n2)/2;
alert(`A média do aluno é: ${m}`);
res.innerHTML(`A média do aluno é: ${m}`)
}
</script>
</body>
</html>
Luiz Felipe, I made the change that you detailed and it happened the following: he writes the answer on the screen but it blinks and then disappears. It’s happened before, I can’t solve this problem right now
– Lucas Mendes
This is because the form is being submitted when you press the button. To resolve this, add the attribute
onsubmit="return false"
in the form (there are other ways to resolve, but in your case this is the simplest). Another option is to change the attributetype="submit"
fortype="button"
on the button.– Luiz Felipe
Luiz Felipe, thank you very much for your help the problem has been solved!
– Lucas Mendes
@Lucasmendes, in this case you can mark this answer as correct/accepted by clicking on the " " that is next to it, which also marks your question as solved. :-)
– Luiz Felipe