How to generate an event by clicking on a checkbox with javascript?

0

I have the following code, what it does is add variables and place the final result in an input, now what I want is that when you click on a checkbox, add 5 to the total result and update the input with the new value , and if I click again on the check, I will subtract those 5 that I added and update again.

var uno = $("#input1").val();
var dos = $("#input2").val();
var tres = $("#input3").val();

var total = uno * 1.5 +  dos * 0.5 + tres * 0.5;
document.getElementById("total").value = total;



<input name="total" id="total" class="form-control"/>

<label><input id="agregar" type="checkbox" value="">Option 2</label>
    
asked by Root93 11.09.2018 в 05:37
source

2 answers

2

You could do it through a change event, which you capture when the checkbox changes and then, depending on whether it is selected or deselected, add or subtract 5 from the variable > total .

JQUERY

var total = 10;

$('#agregar').change(function () {
    if($(this).prop('checked') == true) {
    total = total + 5;
  }
  else {
    total = total - 5;
  }

  alert(total);

});

Then, to insert the value of the total variable into the input , you would use the val() function.

JQUERY

var total = 10;

$('#agregar').change(function () {
    if($(this).prop('checked') == true) {
    total = total + 5;
  }
  else {
    total = total - 5;
  }

  $('#total').val(total);

});

As you can see, the only thing I've done has been to change the output on the screen (the alert ) by inserting the variable into the input text . . p>     

answered by 11.09.2018 / 09:06
source
1

This is how I would do it using JavaScript. Keep in mind that the value of an input is a text string. It is also possible that some user leave some input empty or put a value that is not a number. I hope you find it useful.

agregar.addEventListener("change", function(){
  var uno = esNumero(input1.value);
  var dos = esNumero(input2.value);
  var tres = esNumero(input3.value);
  console.log(uno,dos,tres)
  var suma = uno * 1.5 +  dos * 0.5 + tres * 0.5;
  total.value = suma;
})

function esNumero(n) {
  return (!isNaN(parseFloat(n)) && isFinite(n)) ? parseFloat(n) : 0;
}
<input name="input1" id="input1"  placeholder="input1" />
<input name="input2" id="input2"  placeholder="input2" />
<input name="input3" id="input3"  placeholder="input3" />

<input name="total" id="total" class="form-control" placeholder="total" />

<label><input id="agregar" type="checkbox" value="">Option 2</label>
    
answered by 11.09.2018 в 10:29