Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

143
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda