Created
August 21, 2018 16:27
-
-
Save isaquebressy/070cd9de1bef4660402654367874651c to your computer and use it in GitHub Desktop.
Soma valores de itens marcados em checkbox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var totalEl = document.querySelector("#total"); // Pego o valor total para manipular | |
document.querySelectorAll("input").forEach(function(el, i, arr){ // pegando todas as tags inputs para manipular. O forEach faz um loop em cada uma tag | |
var preco = parseInt(el.getAttribute("data-preco")); // pega a tag (el) e acessa o propriedade data-preco da tag e grava na var preco | |
el.onclick = function(e) { // modifica a funcao de click para reagir ao click no checkbox | |
if (el.checked) // verifica se o checkbox foi marcado ou desmarcado | |
totalEl.innerText = parseInt(totalEl.innerText) + preco; // Se foi marcado, soma o valor do total com o preco daquele checkbox | |
else | |
totalEl.innerText = parseInt(totalEl.innerText) - preco; // Se foi desmarcado, subtrai do valor preco daquele checkbox | |
}; | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Teste</title> | |
<link rel="stylesheet" type="text/css" href="./soma-stylesheet.css"/> | |
</head> | |
<body> | |
<form> | |
<input type="checkbox" name="item1" data-preco="1"/> item 1 (valor=1)<br/> | |
<input type="checkbox" name="item2" data-preco="2"/> item 2 (valor=2)<br/> | |
<input type="checkbox" name="item3" data-preco="4"/> item 3 (valor=4)<br/> | |
<input type="checkbox" name="item4" data-preco="8"/> item 4 (valor=8)<br/> | |
<input type="checkbox" name="item5" data-preco="16"/> item 5 (valor=16)<br/> | |
<input type="checkbox" name="item6" data-preco="32"/> item 6 (valor=32)<br/> | |
<input type="checkbox" name="item7" data-preco="64"/> item 7 (valor=64)<br/> | |
</form> | |
<div> | |
<span id="total">0</span> | |
</div> | |
<script type="text/javascript" src="./soma-checkbox.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#total { | |
display:block; | |
margin-top: 30px; | |
font-size:100px; | |
font-weight: bold; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment