0
My JS variable is not saving a certain value, the idea is that by clicking on the checkbox and sending, the user receives the number equivalent to that checkbox. However it shows the value and then immediately refreshes the page and hides the value.
HTML code:
<form>
<label for="campo1">Campo 1</label>
<input type="checkbox" id="campo1">
<label for="campo2">Campo 2</label>
<input type="checkbox" id="campo2">
<label for="campo3">Campo 3</label>
<input type="checkbox" id="campo3">
<label for="campo4">Campo 4</label>
<input type="checkbox" id="campo4">
<label for="campo5">Campo 5</label>
<input type="checkbox" id="campo5">
<input type="submit" id="btn">
</form>
<input type="text" id="progress">
JS Code
<script type="text/javascript">
var cp1 = document.getElementById("campo1");
var cp2 = document.getElementById("campo2");
var cp3 = document.getElementById("campo3");
var cp4 = document.getElementById("campo4");
var cp5 = document.getElementById("campo5");
document.getElementById("btn").onclick = function() {
progress = 0;
if (cp1.checked) {
progress = progress + 20;
}
if (cp2.checked) {
progress = progress + 20;
}
let input = document.getElementById("progress");
input.value = progress;
}
</script>
Complete code:
<!DOCTYPE html>
<html>
<head>
<title>Teste de porcentagem</title>
</head>
<body>
<form>
<label for="campo1">Campo 1</label>
<input type="checkbox" id="campo1">
<label for="campo2">Campo 2</label>
<input type="checkbox" id="campo2">
<label for="campo3">Campo 3</label>
<input type="checkbox" id="campo3">
<label for="campo4">Campo 4</label>
<input type="checkbox" id="campo4">
<label for="campo5">Campo 5</label>
<input type="checkbox" id="campo5">
<input type="submit" id="btn">
</form>
<input type="text" id="progress">
<script type="text/javascript">
var cp1 = document.getElementById("campo1");
var cp2 = document.getElementById("campo2");
document.getElementById("btn").onclick = function() {
progress = 0;
if (cp1.checked) {
progress = progress + 20;
}
if (cp2.checked) {
progress = progress + 20;
}
let input = document.getElementById("progress");
input.value = progress;
}
</script>
</body>
</html>
thanks since <3
Curious that in the two if’s the result is the same.
– Sam
Exactly, I wanted the result to be saved in the variable Progress precisely to add with the result of the following if’s, and thus save the progress, starting at 0, then 0 + 20, 20 + 20 and so on.
– Jefferson Rodrigues
Then you don’t need two if’s. Just one:
if (cp1.checked || cp2.checked) { progress = progress + 20; }
– Sam
But in this case it will not give the new value to the Press only if all fields are checked? Because the IF condition structure using AND will understand q can only assign the value if all fields have been marked, n is that q want
– Jefferson Rodrigues
No, Brow. If one or the other is checked. The
||
means OR.– Sam