Javascript sum or subtract by clicking checkbox

Asked

Viewed 1,131 times

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?

  • 3

    Yes, to begin with it is not allowed to have more than one element with the same ID on the page.

  • Better use class?

  • Or create a meaningful (and unique) name for each checkbox.

  • But then how to do it recognize several Ids? I can even put based on ID.

2 answers

1

Follow an example using Jquery.

var total = 0;
//Chama a função com click em qualquer checkbox
$(':checkbox').click(function() {
  //Atribui o valor do input p/ variável 'valor'
  var valor = parseInt($(this).val());
  //Se o checkbox for marcado ele soma se não subtrai
  if ($(this).is(":checked")) {
    total += valor;
  } else {
    total -= valor;
  }
 //Atribui o valor ao input
  $("#evento_value").val(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="evento_value1" value="99.00">
<input type="checkbox" id="evento_value2" value="120.00">
<input type="checkbox" id="evento_value3" value="99.00">
<input type="checkbox" id="evento_value4" value="300.00">
<input type="checkbox" id="evento_value5" value="5.00">

<input type="text" id="evento_value" onclick="AddValor()">

  • 1

    I would prefer to use $(':checkbox'). click(Function() { e not $('input'). click(Function() {, to avoid unexpected behavior in case the form has other inputs.

  • 1

    @Marcellalves for sure, it is always good to avoid, corrected.

1

With javascript, to avoid code redundancy it is possible to insert an event in all checkbox, something more or less like:

var inputs = document.querySelectorAll('input[type="checkbox"]');
for (let i = 0; i < inputs.length; i++) {
  inputs[i].addEventListener('click', AddValor);
}

function AddValor() {
  var resultado = parseFloat(this.value, 10);
  var principal = document.getElementById('valor_principal');
  var total = parseFloat(principal.value, 10);

  this.checked == true ? total += resultado : total -= resultado;

  principal.value = total;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="evento_value1" value="99.00">
<input type="checkbox" id="evento_value2" value="120.00">
<input type="checkbox" id="evento_value3" value="99.00">
<input type="checkbox" id="evento_value4" value="300.00">
<input type="checkbox" id="evento_value5" value="5.00">

<input id="valor_principal" value="100">

  • Thank you Lucas Costa...

  • I only have 2 more problems. Can you help me? This series of inputs open automatically after I select an option in a select. That is, I select an option in a select, it brings the appropriate information to the option and within it there is this series of inputs. The fact is that if I put this code that way it doesn’t work, but if I put it right on the page, it works... Do you have any idea what it might be?

  • The other problem is that this value needs to be updated in some inputs, that is, it would have several <input id="main value"="100"> to be updated. Is it possible to do this? That is, by clicking on the checkbox it updates all input fields?

  • It is possible yes, for the two doubts @Rafaelschaffergimenes. In the case of the first, I did not understand as well as to work inside the page. If you mean that within a separate . js does not work, maybe the . js is not being loaded or this code is running in the upload, ideally run in the change event select, entente?!

  • In the second case, the id of each element must be unique, cannot be repeated. Therefore you will have to use another selector, as a class for example. If you still can’t, create a Jsfiddle showing how far you can get me to help you =]

  • I tried to use class, but it didn’t work... In fact, I changed Document.getElementById('main value_main') to Document.getElementByClass('main value_main') and then I thought it really wouldn’t work because it would need somehow to calculate the value for each input <>...

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.