Taking value from one input and moving to another dynamically

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 (which comes the value of the product) p>

So far so good, but I'm having trouble at the following point:

I want to get the value of the product with the onchange of the select and move to that input on the side.

This way:

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 the second select. And I do not want that.

Here is an example image:

Added html structure when clicked on the "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>

    
asked by anonymous 13.08.2017 / 03:52

1 answer

2

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

onchange="showValue(this)"

This way you will pass the reference of the select element, not just its value; and in the showValue function, the idea would be to first fetch the parent element div.form-inline so that you can search within this element input.value-prod , so you would select the prod_value field that is in the same div of select as was changed. The code would look 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);
    }
  );
}
    
13.08.2017 / 04:13