Taking value from one input and passing to another dynamically

Asked

Viewed 104 times

1

I have a screen to sell products, with this I have a button to add product to be sold, this button brings a select (to choose the product to be sold) and an input (that comes the value of the product)

So far so good, but I’m struggling on the following point:

I want to catch with the onchange of select the product value and pass to that next input.

Thus:

function showValue(value) {
    var table  = $('.value-prod');
    $.post('ajax/value_prod.php', {value: value, select: true}, function(return){
        $(table).val(
            return    
        );
    });
}

This works in part, what happens is that if I add another product, it will replace the value of the previous input with that of the second select. And I don’t want that.

Follow an example image:inserir a descrição da imagem aqui

Added html structure when clicked on "product button":

<div class="form-inline">
<label>Novo Produto</label>
<input class="form-control" name="prod_qtd[]" placeholder="Quantidade" type="number">
<select class="select-here form-control" name="prod_id[]" onchange="showValue(this.value)"><option value="" selected="">Selecione um produto</option>
    <option value="5">Pneu</option>
    <option value="6">camara de ar</option>
</select>
<input class="form-control value-prod" name="prod_value[]" value="" placeholder="Valor" type="text">
<a href="#" class="remove_field"><span aria-hidden="true">×</span></a>

  • 1

    Put the HTML structure that is added to each product in question as well.

1 answer

2


The way that would solve this problem is to change the call from the event to:

onchange="showValue(this)"

because then you will pass the element reference select, not only its value; and in function showValue, the idea would be you first seek the parent element div.form-inline to be able to search within this element input.value-prod, so you would select the field prod_value that is in the same div of select changed. The code would be something like:

function showValue(element) {
  const prod_value = $(element).parent(".form-inline").children(".value-prod");

  $.post(
    'ajax/value_prod.php',
    {value: element.value, select: true},
    function (data) {
      prod_value.val(data);
    }
  );
}
  • Thank you very much guy helped me a lot.

Browser other questions tagged

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