Doubt with dynamic field creation with jquery + php

1

Hello! I'm doing a simple program for managing my beers and sales.

In the order view, I was able to add a new line to add a new item to the order.

  

Fields: id_item (select) | id_lote_item (select) | quantity (text) | unit value (text) | subtotal (text)

jquery code that adds fields:

var campos_max = 10;   //max de 10 campos
var x = 1; // campos iniciais
$('#add_field').click(function (Event) {
    Event.preventDefault();     //prevenir novos clicks
    if (x < campos_max) {
        $('#listas').append('\
            <div id="linha">\n\
                <div class="col-sm-3">\n\
                    <div class="form-group">\n\
                        <label for="exampleInputEmail1">Cerveja</label>\n\
                        <select name="id_item_estoque_pedido[]" id="id_item" class="select2 form-control">\n\
                            <option>Selecione</option>\n\
                        </select>\n\
                    </div>\n\
                </div>\n\
                <div class="col-sm-3">\n\
                    <div class="form-group">\n\
                        <label for="exampleInputEmail1">Lote</label>\n\
                        <select name="id_lote_pedido[]" id="id_lote_item" class="select2 form-control">\n\
                            <option>Selecione o lote</option>\n\
                        </select>\n\
                    </div>\n\
                </div>\n\
                <div class="col-sm-2">\n\
                    <div class="form-group">\n\
                        <label for="exampleInputEmail1">Qtd. Pedido</label>\n\
                        <input type="text" name="quantidade_item_pedido[]" id="quantidade_item_pedido" class="form-control">\n\
                    </div>\n\
                </div>\n\
                <div class="col-sm-2">\n\
                    <div class="form-group">\n\
                        <label for="exampleInputEmail1">valor Unitario</label>\n\
                        <input type="text" name="valor_unitatio_item_pedido[]" id="valor_unitatio_item_pedido" class="form-control">\n\
                    </div>\n\
                </div>\n\
                <div class="col-sm-2"><div class="form-group">\n\
                    <label for="exampleInputEmail1">Subtotal</label>\n\
                    <input type="text" id="subtotal_item_pedido" class="form-control" readonly="true">\n\
                </div>\n\
            </div>'
        );
        x++;
    }
});

So long, my doubts come now ... The id_lote_item field is changed to display the batches of the selected item.

jquery code:

$('#id_item').change(function (e) {
    var item = $('#id_item').val();
    var base_url = '<?php echo base_url(); ?>';
    $.getJSON(base_url + 'pedido/GetLoteByIdItem/' + item, function (dados) {

        if (dados.length > 0) {
            var option = '<option>Selecione o lote</option>';
            $.each(dados, function (i, obj) {
                option += '<option value="' + obj.id_lote + '">' + obj.nome_lote + ' - ' + 'Qtd: (' + obj.quantidade_garrafas_lote + ')</option>';
            })
        } else {
            option = '<option>Selecione o lote</option>';
        }
        $('#id_lote_item').html(option).show();
    });
});

I was able to do for only one line. Now with this dynamic lines scheme I could not even get the stick.

Thanks for the help!

    
asked by anonymous 14.06.2017 / 08:33

2 answers

2

What is the problem?

There are two problems in the code:

One of them is $('#id_item') does not run because '#id_item' did not exist when this code ran, you need to use delegation of events .

The other is that joining multiple lines with #id_item will generate duplicate IDs, and this is invalid HTML syntax.

How to resolve:

Since you can not use duplicate IDs, I suggest you change everything ID (in that HTML code of each line) to classes , or by removing IDs and using name (as I did in the example) / p>

So you can always work line by line with jQuery using 3 tools:

  • .closest() to find the top of the line
  • .find() to find an element in the descending DOM
  • .on() to delegate events.

So your jQuery code would look like:

$('#listas').on('change', '[name="id_item_estoque_pedido[]"]', function(e) {
  var item = this;
  var base_url = '<?php echo base_url(); ?>';
  $.getJSON(base_url + 'pedido/GetLoteByIdItem/' + this.value, function(dados) {

    if (dados.length > 0) {
      var option = '<option>Selecione o lote</option>';
      $.each(dados, function(i, obj) {
        option += '<option value="' + obj.id_lote + '">' + obj.nome_lote + ' - ' + 'Qtd: (' + obj.quantidade_garrafas_lote + ')</option>';
      })
    } else {
      option = '<option>Selecione o lote</option>';
    }
    $(item).closest('.linha').find('[name="id_lote_pedido[]"]').html(option).show();
  });
});

So in HTML you just have to change

id="linha"

for

class="linha"
    
14.06.2017 / 08:52
0

You will only be able to user the event into something created later, if it is started like this:

$(document).on('change','.elemento_da_interação', function(e) {

Detail that ids do not duplicate, use className.

    
14.06.2017 / 13:32