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

398
Visualizações
Get array of inputs value created using DOM in jQuery

I have this form here

enter image description here

and I want to prevent submit the form as long as the inputs value is not equal to 100, In other words, to complete and save, the values of all inputs must be equal to 100

How to do this given that the inputs are created by DOM as the following picture :

url: '/getProjectStandards/' + standid,
        type: "get",
        async: true,
        dataType: "json",
        success: function (data2) {
            console.log(data2);
            $.each(data2, function (key, value) {
                $('#inner_sugg').append('<div class="row mt-1">' +
                    '<div class="col-6">' +
                    '<p class="">' + value['stand_name'] + '</p>' +
                    '</div>' +
                    '<div class="col-6">' +
                    '<input type="hidden" class="form-control col-3" name="stand_id[]" value="' + value['id'] + '">' +
                    '<input type="number" min="0" class="form-control col-3 sugg_weight" name="sugg_weight[]" required">' +
                    '</div>' +
                    '</div>'
                );

            });

});

how to get all the inputs value on submit and validate that they are equal to 100 ?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  • Fix your name values.
    Should be name="sugg_weight[]", not name="sugg_weight[] required"
  • Use event delegation with the .on() Method $staticParent.on("eventname", "dynamicChild", fn)
  • Anternatively use just $staticParent.on("eventname", fn) considering Event propagation (meaning that a static parent can be notified of any events propagated from any static or dynamic child element).
  • Use Array.prototype.reduce to reduce your dynamic input's values to a Number

const $innerSugg = $("#inner_sugg");

const toggleSuggSubmit = () => {
  const $inputs = $("[name='sugg_weight[]']", $innerSugg);
  const $submit = $("[type='submit']", $innerSugg);
  
  const total = $inputs.get().reduce((tot, el) => tot += parseFloat(el.value??0), 0);
  $submit.prop({disabled: total !== 100});
};

$innerSugg.on("input", "[name='sugg_weight[]']", toggleSuggSubmit);

// Just to fake "AJAX generated" inputs at a later time...
$innerSugg.prepend(`
  <input type="number" name="sugg_weight[]" required>
  <input type="number" name="sugg_weight[]" required>
  <input type="number" name="sugg_weight[]" required>
`);
<form id="inner_sugg">
  = 100 <button type="submit" disabled>SUBMIT</button>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

or you could also use simply $innerSugg.on("input", toggleSubmit); exploiting event propagation.

const $innerSugg = $("#inner_sugg");

const toggleSuggSubmit = () => {
  const $inputs = $("[name='sugg_weight[]']", $innerSugg);
  const $submit = $("[type='submit']", $innerSugg);
  
  const total = $inputs.get().reduce((tot, el) => tot += parseFloat(el.value??0), 0);
  $submit.prop({disabled: total !== 100});
};

$innerSugg.on("input", toggleSuggSubmit);

// Just to fake "AJAX generated" inputs at a later time...
$innerSugg.prepend(`
  <input type="number" name="sugg_weight[]" required>
  <input type="number" name="sugg_weight[]" required>
  <input type="number" name="sugg_weight[]" required>
`);
<form id="inner_sugg">
   = 100 <button type="submit" disabled>SUBMIT</button>
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

about 4 years ago · Juan Pablo Isaza Relatório

0

function canISave() {
  const inputs = document.querySelectorAll("input[name='sugg_weight[]']");

  let total = 0;

  inputs.forEach((i) => total += (parseInt(i.value) || 0));

  // console.log(total);

  document.querySelector('#submit').disabled = total !== 100;
}
input {
  display: block;
}
<input type="number" name="sugg_weight[]" oninput="canISave()" />
<input type="number" name="sugg_weight[]" oninput="canISave()" />
<input type="number" name="sugg_weight[]" oninput="canISave()" />
<br>
<input id="submit" type="submit" disabled />

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