title: jQuery: Value of an input doesn't save in a variable
body: <p>I can't save what I have in my input in a variable. It saves as a blank space or if it's an integer: 0</p>
  
  <p>This is my code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>function attachKeyupEventDescuento(inputElement, i) {
    var cantidad = $('#txt_compras_cantidad' + i).val()
    var costo = $('#txt_compras_costoUni' + i).val()
    total = (cantidad * costo)
    $(inputElement).keyup(function() {
      console.log(total)
      if (inputElement.val() !== '') {
        var descuento = inputElement.val()
        var descuentoTotal = ($('#txt_compras_cantidad' + i).val() * $('#txt_compras_costoUni' + i).val()) - ($('#txt_compras_cantidad' + i).val() * $('#txt_compras_costoUni' + i).val() * (descuento / 100))
        $('#spn_compras_total' + i).text(descuentoTotal.toFixed(2))
        sumarprecioFinal()
      } else {
        $('#spn_compras_total' + i).text(($('#txt_compras_cantidad' + i).val() * $('#txt_compras_costoUni' + i).val()).toFixed(2))
      }
    })
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Let me explain the code:</p>
  
  <pre><code>var cantidad = $('#txt_compras_cantidad' + i).val()
  var costo = $('#txt_compras_costoUni' + i).val()
  </code></pre>
  
  <p>If I save them in those variables, I get a blank space, but if I use them without saving them in a variable, they work perfectly. Why does it happen?</p>
  
  <p>This function is called from a button that created a new row in my table. The <code>inputelement</code> is the current input on which to attach the <code>keyup</code> event.</p>