Tengo un formulario simple que recorre algunos elementos seleccionados del servidor. En este caso, quiero sumar cada valor de opción que seleccioné y no el deshabilitado y mostrar el cálculo de estos valores en el valor de entrada cada vez que el usuario cambie el valor dentro de él. ¿Cómo funciona con el evento onchage? Gracias por adelantado.

Ejemplo de código HTML

<form>
  <div class="form-group">
    <select class="1 presence-value form-control" name="presence-value" required>
      <option value="">-- Select--</option>
      <option value="1" selected>Full</option>
      <option value="0.5">Half</option>
      <option value="0">None</option>
    </select>
  </div>
  <div class="form-group">
    <select class="1 presence-value form-control" name="presence-value" required>
      <option value="">-- Select--</option>
      <option value="1" selected>Full</option>
      <option value="0.5">Half</option>
      <option value="0">None</option>
    </select>
  </div>
  
  <div class="form-group">
    <select class="2 presence-value form-control" name="presence-value" disabled required>
      <option value="">-- Select--</option>
      <option value="1">Full</option>
      <option value="0.5">Half</option>
      <option value="0" selected>None</option>
    </select>
  </div>
  <div class="form-group">
    <select class="2 presence-value form-control" name="presence-value" disabled required>
      <option value="">-- Select--</option>
      <option value="1">Full</option>
      <option value="0.5">Half</option>
      <option value="0" selected>None</option>
    </select>
  </div>

  <input type="number" value="0" required>
  <button type="submit">Submit</button>
</form>
1
Michel Setyawan Mulyono 13 jul. 2021 a las 09:36

3 respuestas

La mejor respuesta

Filtrar, mapear y reducir

$(function() {
  const sumSels = () => $("#total").val($sels
    .filter(":enabled") // this is not strictly needed in your case
    .map(function() { return +this.value })
    .get()
    .reduce((a, b) => a + b)
    .toFixed(2));

  const $sels = $('[name="presence-value"]');
  $sels.on("change", sumSels); // event handler
  sumSels(); // initialise on load
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <select class="1 presence-value form-control" name="presence-value" required>
      <option value="">-- Select--</option>
      <option value="1" selected>Full</option>
      <option value="0.5">Half</option>
      <option value="0">None</option>
    </select>
  </div>
  <div class="form-group">
    <select class="1 presence-value form-control" name="presence-value" required>
      <option value="">-- Select--</option>
      <option value="1" selected>Full</option>
      <option value="0.5">Half</option>
      <option value="0">None</option>
    </select>
  </div>

  <div class="form-group">
    <select class="2 presence-value form-control" name="presence-value" disabled required>
      <option value="">-- Select--</option>
      <option value="1">Full</option>
      <option value="0.5">Half</option>
      <option value="0" selected>None</option>
    </select>
  </div>
  <div class="form-group">
    <select class="2 presence-value form-control" name="presence-value" disabled required>
      <option value="">-- Select--</option>
      <option value="1">Full</option>
      <option value="0.5">Half</option>
      <option value="0" selected>None</option>
    </select>
  </div>

  <input type="number" value="0" readonly id="total">
  <button type="submit">Submit</button>
</form>
3
mplungjan 13 jul. 2021 a las 06:58

Puede simplemente escuchar el evento de cambio de cualquiera de las selecciones, luego sumar sus valores juntos

$(document).ready(function() {
  $('select').change(function() {
    let total = 0;
    $('select').each(function() {
      total += +$(this).val()
    })
    console.log('the total is', total)
    $('[name=total]').val(total)
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <div class="form-group">
    <select class="1 presence-value form-control" name="presence-value" required>
      <option value="">-- Select--</option>
      <option value="1" selected>Full</option>
      <option value="0.5">Half</option>
      <option value="0">None</option>
    </select>
  </div>
  <div class="form-group">
    <select class="1 presence-value form-control" name="presence-value" required>
      <option value="">-- Select--</option>
      <option value="1" selected>Full</option>
      <option value="0.5">Half</option>
      <option value="0">None</option>
    </select>
  </div>

  <div class="form-group">
    <select class="2 presence-value form-control" name="presence-value" disabled required>
      <option value="">-- Select--</option>
      <option value="1">Full</option>
      <option value="0.5">Half</option>
      <option value="0" selected>None</option>
    </select>
  </div>
  <div class="form-group">
    <select class="2 presence-value form-control" name="presence-value" disabled required>
      <option value="">-- Select--</option>
      <option value="1">Full</option>
      <option value="0.5">Half</option>
      <option value="0" selected>None</option>
    </select>
  </div>

  <input name='total' type="number" value="0" required>
  <button type="submit">Submit</button>
</form>
2
Kinglish 13 jul. 2021 a las 06:51

Necesita usar document.querySelectorAll('select') para obtener todas las etiquetas seleccionadas y luego por selectedOptions obtener el valor seleccionado de cada etiqueta seleccionada y calcular la suma de ellas.

Todas las acciones anteriores están en un método (digamos getSum) que puede vincular con onchange="getSum()" de cada etiqueta de selección.

Tenga en cuenta que esta solución se basa en código javascript puro y no uso ninguna biblioteca js.

function getSum() {
            var selectes = document.querySelectorAll('select');
            sum = 0;
            for (var i = 0; i < selectes.length; i++) {
                sum += +selectes[i].value;
            }
            document.getElementById("submited").value = sum;
        }
<form>
        <div class="form-group">
            <select class="1 presence-value form-control" name="presence-value" required onchange="getSum()">
                <option value="">-- Select--</option>
                <option value="1" selected>Full</option>
                <option value="0.5">Half</option>
                <option value="0">None</option>
            </select>
        </div>
        <div class="form-group">
            <select class="1 presence-value form-control" name="presence-value" required onchange="getSum()">
                <option value="">-- Select--</option>
                <option value="1" selected>Full</option>
                <option value="0.5">Half</option>
                <option value="0">None</option>
            </select>
        </div>

        <div class="form-group">
            <select class="2 presence-value form-control" name="presence-value" disabled required onchange="getSum()">
                <option value="">-- Select--</option>
                <option value="1">Full</option>
                <option value="0.5">Half</option>
                <option value="0" selected>None</option>
            </select>
        </div>
        <div class="form-group">
            <select class="2 presence-value form-control" name="presence-value" disabled required onchange="getSum()">
                <option value="">-- Select--</option>
                <option value="1">Full</option>
                <option value="0.5">Half</option>
                <option value="0" selected>None</option>
            </select>
        </div>

        <input id="submited" type="number" value="0" required>
        <button type="submit">Submit</button>
2
Alireza Ahmadi 13 jul. 2021 a las 07:42