Capture input value dynamically with Jquery

Asked

Viewed 638 times

4

I’m having a problem where I need to multiply the value of two input fields (price and quantity) to play in a third field (product price). My problem occurs where I try to get the value of these first two input with Jquery, and the value that is returned to me is Undefined. I believe the problem occurs because, the price value is brought directly from the Database as soon as the user chooses the desired product in the field of "Products", and this value is also constantly changed. The value of the quantity field comes as default 0 and the user can also change to as much as his need. How do I manage to store the value of these two inputs and multiply them dynamically, where whenever the value of each one is changed, the function accompanies and brings the correct multiplication value ?

The HTML code of the product part:

<div class="produtos-wrap" id="clone-produtos">
            <div class=" text-center select_height">
                <b>Número:</b>
                <div id="index" class="font-pop">1</div>
            </div>

            <div class=" select_height" id="div_produtos">
                <b>Produto:</b>
                <select class="selectpicker form-control" data-show-subtext="false" data-live-search="true"
                        name="select_produtos" id="select_produtos" onchange="initProdutos()">
                    <?php
                    foreach ($result2 as $item_fornecedores) {
                        echo '<option data-subtext="' . $item_fornecedores['desc_produto'] . '" value="'
                            . $item_fornecedores['desc_produto'] . '">' . $item_fornecedores['desc_produto'] . '</option>';
                    }
                    ?>
                </select>
            </div>

            <div class="text-center select_height">
                <b>Embalagem:</b>
                <br>
                <input type="text" maxlength="2" class="edit-input font-pop" id="embalagem" name="embalagem" value="">
            </div>

            <div class="text-center select_height">
                <b>Preço:</b>
                <br>
                <input type="text" maxlength="5" id="preco" name="preco" class="edit-input font-pop">
            </div>

            <div class="text-center select_height">
                <b>Quantidade:</b>
                <br>
                <input type="text" maxlength="3" class="edit-input font-pop" value="0" id="quantidade-produto" name="quantidade-produto" onchange="onLoad()">
            </div>

            <div class="text-center select_height">
                <b>Preço do Produto:</b>
                <div id="preco-produto" class="font-pop"></div>
            </div>

            <div class="text-center select_height">
               <button id="remove">X</button>
            </div>

        </div>

The way I was trying to get the value of variables in Jquery:

function onLoad() {
    var $preco = $("#preco").value;
    alert($preco);

    var $qtd = $("#quantidade-produto").value;
    console.log($qtd);
}

As requested, the code that is brought through the select is this:

http://prntscr.com/nssevt

And the JSON that comes from the Bank is as follows:

http://prntscr.com/nssg23

Code of initProducts() as requested:

function initProdutos(){
    var letras_produtos = document.getElementById("select_produtos").value;
    $.ajax({
        type: "GET",
        url: "API.php",
        data: {
            "mode": "produtos",
            "letras_produtos": letras_produtos
        },
        dataType:"JSON",
        //CASO DÊ TUDO CERTO
        success:function(data){
            console.log(data);
            document.getElementById('embalagem').value = data[0]['embalagem'];
            document.getElementById('preco').value = data[0]['preco_base'];
        },
        error:function(request, error)
        {
            console.log("Request: " + JSON.stringify(request));;
        }
    });
}

2 answers

2


Create a function to recalculate the values and listen to changes in them that invoke the calling of this function. Something like this:

$(function() {

  const $preco = $("#preco");
  const $qtd = $("#quantidade-produto");
  const $total = $("#preco-produto");

  function recalculate() {
    const total = Number($preco.val() || 0) * Number($qtd.val() || 0);
    $total.text(total);
  }

  function initProdutos() {
    var letras_produtos = $("#select_produtos").val();
    $.ajax({
      type: "GET",
      url: "API.php",
      data: {
        "mode": "produtos", letras_produtos
      },
      dataType: "JSON",
      //CASO DÊ TUDO CERTO
      success: function(data) {
        console.log(data);
        $('#embalagem').val(data[0]['embalagem']);
        $preco.val(data[0]['preco_base']);
        recalculate();
      },
      error: function(request, error) {
        console.log("Request: " + JSON.stringify(request));;
      }
    });
  }

  $preco.on('input', recalculate);
  $qtd.on('input', recalculate);
  recalculate();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-center select_height">
  <b>Preço:</b>
  <br>
  <input type="text" maxlength="5" id="preco" name="preco" class="edit-input font-pop" value="0">
</div>

<div class="text-center select_height">
  <b>Quantidade:</b>
  <br>
  <input type="text" maxlength="3" class="edit-input font-pop" value="1" id="quantidade-produto" name="quantidade-produto">
</div>

<div class="text-center select_height">
  <b>Preço do Produto:</b>
  <div id="preco-produto" class="font-pop"></div>
</div>

0

Good morning.

I would encapsulate the inputs in a common div and use the following:

var qtd = 0, result = 0;
$('#container input').each(function(){
    if(($(this).attr('name') == 'quantidade'){
        qtd = $(this).val();
    }else if($(this).attr('name') == 'valor-prod'){
        result = (qtd * $(this).val());
    }
});
$('#input-total').val(result);
  • I invented the ids and names of imputs to be faster, but I think it’s understandable.

Put this in a role and create an event to run it.

Browser other questions tagged

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