Sum of inputs Checkbox and Text Real time

2

I need to add the text type input with the checkbox type input, at this moment when I click on the checkbox it adds up and shows the total, but I need to add the text type input called service price.

This is a screenshot of my form:

This is my code:

<?php foreach($servicelist as $listsv): ?>
<input name="service[]" type="checkbox" onClick="if (this.checked) sumar(<?php echo $listsv["price"]; ?>); else restar(<?php echo $listsv["price"]; ?>)" value='<?php echo $listsv["id"]; ?>'><?php echo utf8_encode($listsv['service']); ?><br>
<?php endforeach; ?>
<br>

This is my function

var total = 0;

function sumar(valor) {
    total += valor;
    document.formulario.total.value = '$' + total.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

function restar(valor) {
    total -= valor;
    document.formulario.total.value = '$' + total.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

function otro_servicio() {
    $("#lineas").append('<label>Nombre Servicio</label>');
    $("#lineas").append('<input name="othersv" type="text" class="form-control importe_linea" placeholder="Nombre del servicio extra"/><br/>');
    $("#lineas").append('<label>Precio Servicio</label>');
    $("#lineas").append('<input name="price" type="text" class="form-control importe_linea" placeholder="Precio del servicio"/><br/>');
}

To achieve this goal I can use javascript, jquery or angular.

    
asked by ByGroxD 21.02.2017 в 18:09
source

3 answers

4

You could save the price of the checkbox elements as an attribute of these elements and then add a listener to the click of the checkboxes and the input keyup.

$(document).ready(function() {
 
 $(document).on('click keyup','.mis-checkboxes,.mis-adicionales',function() {
   calcular();
 });

});

function calcular() {
  var tot = $('#total');
  tot.val(0);
  $('.mis-checkboxes,.mis-adicionales').each(function() {
    if($(this).hasClass('mis-checkboxes')) {
      tot.val(($(this).is(':checked') ? parseFloat($(this).attr('tu-attr-precio')) : 0) + parseFloat(tot.val()));  
    }
    else {
      tot.val(parseFloat(tot.val()) + (isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val())));
    }
  });
  var totalParts = parseFloat(tot.val()).toFixed(2).split('.');
  tot.val('$' + totalParts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",") + '.' +  (totalParts.length > 1 ? totalParts[1] : '00'));  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><input type="checkbox" tu-attr-precio="3.5" class="mis-checkboxes" /> Elemento #1</li>
  <li><input type="checkbox" tu-attr-precio="7.5" class="mis-checkboxes" /> Elemento #2</li>
  <li><input type="checkbox" tu-attr-precio="5.5" class="mis-checkboxes" /> Elemento #3</li>
  <li><input type="checkbox" tu-attr-precio="4.5" class="mis-checkboxes" /> Elemento #4</li>
</ul>

<label><strong>Servicio adicional</strong><label>
<div>
  <input type="text" class="mis-adicionales" placeholder="Precio del servicio"/>
</div>

<label><strong>Total</strong><label>
<div>
  <input id="total" type="text" placeholder="0.00"/>
</div>
    
answered by 21.02.2017 / 20:10
source
0

You can use a Jquery / javascript function like this.

function Sumar() {
    var div = $('#RegistroServicio');
    var divSumar = $(div).find('[name$="price"]');
    var Total = 0;
    var temp = 0;
    for (var i = 0; i < divSumar.length; i++) {

        var Monto = parseFloat(divSumar[i].value).toFixed(2);
        if (Monto === 'NaN') {
            Monto = 0;
        }
        Total = parseFloat(parseFloat(Total) + parseFloat(Monto)).toFixed(2);

    }
    $('#suma').val(Total);
}

You can add the function in the onclick event of all the price inputs

$("#lineas").append('<input name="price" type="text" class="form-control importe_linea" placeholder="Precio del servicio" onclick="Sumar()"/><br/>');

And the Service Price input can take the result of the total

<label>Precio del servicio</label>
<input id="suma" name="Total" type="text" value="0" />

I hope and serve you:)

    
answered by 21.02.2017 в 18:34
0

If you want to use javascript, this may be an option:

What the following code does is described this way:

Each time the state of CheckBox changes, it will verify the value of the sum that exists at the moment and if it is checked , it will add the value of the check to the general sum, otherwise , subtract that value from the check.

This is the code:

function actualizarValor(estaChequeado, valor) {

  // Variables.
  var suma_actual = 0;
  var campo_resultado = document.getElementById('txtValor');
  valor = parseInt(valor);

  // Obtener la suma que pueda tener el campo 'txtValor'.
  try {
    if (campo_resultado != null) {

      if (isNaN(campo_resultado.value)) {
        campo_resultado.value = 0;
      }

      suma_actual = parseInt(campo_resultado.value);
    }
  } catch (ex) {
    alert('No existe el campo de la suma.');
  }

  // Determinar que: si el check está seleccionado "checked"
  // entonces, agregue el valor a la variable "suma_actual";
  // de lo contrario, le resta el valor del check a "suma_actual".
  if (estaChequeado == true) {
    suma_actual = suma_actual + valor;
  } else {
    suma_actual = suma_actual - valor;
  }

  // Colocar el resultado de las operaciones anteriores de vuelta
  // al campo "txtValor".
  campo_resultado.value = suma_actual;
}
<div>
  <input type="checkbox" id="chk_1" value="1" onclick="actualizarValor(this.checked, this.value);" /> <span>CheckBox #1</span>
</div>
<div>
  <input type="checkbox" id="chk_2" value="2" onclick="actualizarValor(this.checked, this.value);" /> <span>CheckBox #2</span>
</div>
<div>
  <input type="checkbox" id="chk_3" value="3" onclick="actualizarValor(this.checked, this.value);" /> <span>CheckBox #3</span>
</div>
<div>
  <input type="checkbox" id="chk_4" value="4" onclick="actualizarValor(this.checked, this.value);" /> <span>CheckBox #4</span>
</div>

<div>
  <i>El resultado es </i><input type="text" readonly id="txtValor" value="0" />
</div>
    
answered by 21.02.2017 в 18:47