how do you take a jquery value and store it in a variable?

Asked

Viewed 115 times

-3

I’m looking to make a sum of all the notes with input, added by JQuery,I just can’t get values from JQuery when I press the button +, wanted to know how I can take the values of JQuery when I press the plus button and type in a number,.

inserir a descrição da imagem aqui
Click to see the image in its original size

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ex001</title>
  <script src=" https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <style>
    .qtd {
      margin-top: 5px;
    }
  </style>



</head>

<body>
  <h2>Média de notas</h2>


  <div id="form">
    <input type='number' class="qt" id="qt1" placeholder="Nota">

    <input type="button" class='botão' id="b" value="+">




    <input type="button" class='finalizar' value='Finalizar' onclick="finalizar()">



    <script>
      $('#b').click(function() {
        var gua = $('#form').append('<input type="text" class="qta" id="qtd" placeholder="Nota"> ').val()
        window.alert(gua)



      })

      function finalizar() {





      }
    </script>

</body>

</html>

  • https://api.jquery.com/val/

  • thanks bro, was looking wrong

1 answer

0


To take the value of one input with the JQuery just use the function .val():

const valor = $('#qt1').val();

In your case I deduce that the button + will not read the value but add a new one input and you will only read the value on the button finalizar. With that in mind, it would probably be easier to go through all the inputs with class qt and use the obtained values to make the calculation. I will adapt your code using this form:

const adicionar = () => $('#form').append('<input type="number" class="qt" placeholder="Nota" />');

const finalizar = () => {
  const valores = $('.qt')
    .map((indice, elemento) => parseInt($(elemento).val(), 10))
    .get();

  const soma = valores.reduce((a, b) => a + b);
  const media = (soma / valores.length) || 0;

  console.log(`Média: ${media}`);
};

const inicializar = () => {
  adicionar();
  $('#btnAdicionar').click(adicionar);
  $('#btnFinalizar').click(finalizar);
};

$(document).ready(inicializar);
input {
  margin-top: 5px;
}

div#form {
  width: 300px;
  display: flex;
  flex-direction: column;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Média de notas</h2>
<div id="form"></div>
<input type="button" id="btnAdicionar" value="+" />
<input type="button" id='btnFinalizar' value='Finalizar' />

  • Bro, sensational,I will study your comic,you did in all jquery was not doing so,valeu mesmo mano ajudou muito,I will study this comic well,valeuuuuuuuu

  • Bro, if I could of tips for studying jquery I thank heartfelt bro

Browser other questions tagged

You are not signed in. Login or sign up in order to post.