Skip to content

Instantly share code, notes, and snippets.

@guibranco
Last active December 8, 2018 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guibranco/271cc1999742316bd0611121b104a4c4 to your computer and use it in GitHub Desktop.
Save guibranco/271cc1999742316bd0611121b104a4c4 to your computer and use it in GitHub Desktop.
Soma notas com JS melhorado - Davidson Web - PHP Brasil - Facebook - https://www.facebook.com/groups/nao.tem.biscoito/permalink/10161478291675160/
<html>
<body>
<script>
function getElements(tipo, linha){
return document.querySelectorAll("input[id^='" + tipo + "-" + linha + "-']");
}
function soma(campos, media){
let soma = 0;
for(let i = 0; i < campos.length; i++){
const valor = campos[i].value * 1;
if(valor >= 0 && valor < 11)
soma += campos[i].value * 1;
}
return media ? soma / campos.length : soma;
}
function somaAts(linha) {
document.getElementById("nt-" + linha + "-1").value = soma(getElements("at",linha), false);
}
function somaNts(linha){
document.getElementById("mb-" + linha).value = soma(getElements("nt", linha), true);
}
function monitoraEventos(linha){
getElements("at",linha).forEach(elem => elem.addEventListener("change",function() { somaAts(linha); }));
document.getElementById("nt-" + linha + "-2").addEventListener("change", function(){ somaNts(linha); });
}
</script>
<?php
foreach($linha => $i=>$valores){
?>
<form>
<input id="at-<?php echo $i; ?>-1" type="number" min="0" max="10">
<input id="at-<?php echo $i; ?>-2" type="number" min="0" max="10">
<input id="at-<?php echo $i; ?>-3" type="number" min="0" max="10">
<input id="at-<?php echo $i; ?>-4" type="number" min="0" max="10">
<input id="at-<?php echo $i; ?>-5" type="number" min="0" max="10">
<input id="nt-<?php echo $i; ?>-1" readonly><br>
<input id="nt-<?php echo $i; ?>-2" type="number" min="0" max="10"><br>
<input id="mb-<?php echo $i; ?>" readonly><br>
<script>monitoraEventos(<?php echo $i; ?>);</script>
</form>
<?php } ?>
</body>
</html>
@guibranco
Copy link
Author

TODO: colocar no input o type="number" para só aceitar números, colocar min="0" e max="10"

@guibranco
Copy link
Author

TODO: colocar no input o type="number" para só aceitar números, colocar min="0" e max="10"

Feito!

TODO: limitar o valor pelo JS também!

@guibranco
Copy link
Author

TODO: colocar no input o type="number" para só aceitar números, colocar min="0" e max="10"

Feito!

TODO: limitar o valor pelo JS também!

Feito!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment