0
I need a Javascript that clicking on a checkbox adds up to a total already existing in another input. And when you disable the checkbox you subtract the checkbox value from this total.
I got the following:
<input type="checkbox" id="evento_value" value="99.00" onclick="AddValor()">
<input type="checkbox" id="evento_value" value="120.00" onclick="AddValor()">
<input type="checkbox" id="evento_value" value="99.00" onclick="AddValor()">
<input type="checkbox" id="evento_value" value="300.00" onclick="AddValor()">
<input type="checkbox" id="evento_value" value="5.00" onclick="AddValor()">
And I also have an input with an established value, where the values of clicking on each checkbox should be added. If the user eventually disables the checkbox, the value is subtracted. I’m running the following code for this:
<script>
function AddValor() {
var resultado = parseInt(document.getElementById('evento_value').value, 10);
var total = parseInt(document.getElementById('valor_principal').value, 10);
if(document.getElementById('evento_value').checked == true) {
total = total +resultado;
} else if(document.getElementById('evento_value').checked == false) {
total = total - resultado;
}
$("#valor_principal").val(total);
}
AddValor();
Where #value_main is the input with the already calculated value at which to add or subtract a certain value by clicking on the checkbox.
The fact is that this script only works for the first input checkbox and not for the others. I suspect it is related to the Ids. Would anyone have any suggestions?
Yes, to begin with it is not allowed to have more than one element with the same ID on the page.
– bfavaretto
Better use class?
– Rafael Schaffer Gimenes
Or create a meaningful (and unique) name for each checkbox.
– Marcell Alves
But then how to do it recognize several Ids? I can even put based on ID.
– Rafael Schaffer Gimenes