Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
How to select values from first few text fields with dynamically ordered class name in a jQuery

I want to find the sum of first few text fields values with dynamically ordered class names in a DOM using jQuery.

For example:

    <input type="text" class="abc5">
    <input type="text" class="xyz5">

    <input type="text" class="abc9">
    <input type="text" class="xyz9">

    <input type="text" class="abc4">
    <input type="text" class="xyz4">

    <input type="text" class="abc3">
    <input type="text" class="abc10">
    <input type="text" class="abc2">

how to do select the sum of first two text field values with class name starting with abc? Thanks for the help

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You could do it like this:

$('[class^="abc"]').on("input", function() {
  var n = $('[class^="abc"]').map(function() {
    return $(this).val().match(/^\d+$/) ? +$(this).val() : 0
  }).get().reduce((pv, cv) => {
    return pv + (parseFloat(cv) || 0);
  }, 0)
  console.log(n)
});

This will get all the values where the value is a number and multiply them.

Demo

$('[class^="abc"]').on("input", function() {
  var n = $('[class^="abc"]').map(function() {
    return $(this).val().match(/^\d+$/) ? +$(this).val() : 0
  }).get().reduce((pv, cv) => {
    return pv + (parseFloat(cv) || 0);
  }, 0)
  console.log(n)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="abc5">
<input type="text" class="xyz5">

<input type="text" class="abc9">
<input type="text" class="xyz9">

<input type="text" class="abc4">
<input type="text" class="xyz4">

<input type="text" class="abc3">
<input type="text" class="abc10">
<input type="text" class="abc2">

about 4 years ago · Juan Pablo Isaza Denunciar

0

It will get the first two input fields you can do anything in the body of function.

count=0;
$("input").each(function () {
    if($(this).attr(class).substr(0,3) == "abc") {
        $(this).val();
    
        count++;
        if(count > 1) {
            return;
        }
    }
});
about 4 years ago · Juan Pablo Isaza Denunciar

0

Using vanilla JS, it will only get the values from the first 3 (few) inputs as per your question

// Update function runs when initiated then every time an input is updated
// Just outputs the total to innerHTML of #calcTotal
const update = () => {
  total.innerHTML = `Total: ${values.reduce((sum, a) => sum + a, 0)}`
};

const total = document.getElementById('calcTotal')
const holder = document.getElementById('calcInputs');
const inputs = Array.from(holder.children);

// Empty array to update with for lopp below
const values = [];

// For the first 3 items in inputs[]
for (let i = 0; i < 3; i++) {
  // Push input value into values[]
  values.push(parseFloat(inputs[i].value))
  
  // Event listener updates value in array every time input is changed
  inputs[i].addEventListener('change', (event) => {
    values[i] = parseFloat(inputs[i].value);
    update();
  })
};

update();
body { font-family: sans-serif; margin: 0; }
* { box-sizing: border-box }

#calcInputs { display: flex; flex-wrap: wrap; }
input { margin: 0.5rem; width: calc( (100% / 3) - 1rem ); }

input:nth-of-type(-n+3) {
 color: red;
 font-weight: 900;
}

#calcTotal {
  margin: 0.5rem;
  font-size: 1.25rem;
  font-weight: 900;
}
<div id="calcInputs">
  <input type="number" class="abc5" value="10">
  <input type="number" class="xyz5"value="25">

  <input type="number" class="abc9" value="7">
  <input type="number" class="xyz9" value="99">

  <input type="number" class="abc4" value="2">
  <input type="number" class="xyz4" value="5">

  <input type="number" class="abc3" value="401">
  <input type="number" class="abc10" value="62">
  <input type="number" class="abc2" value="63">
</div>

<div id="calcTotal">Total</div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda