Doubt with dynamic fields creation with jquery + php

Asked

Viewed 169 times

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 include a new item for the order.

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

jquery code adding 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 far so good... my doubt comes now... The id_lote_item field is changed to display 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 managed to make for only one line. Now with this dynamic lines scheme I couldn’t even stick to.

Thanks for the help!

  • In the HTML you are generating there are more than 1 #id_item? I mean, you’re adding multiple times the HTML you have in the question is that? and it only works for the right first?

  • @Sergio, when I call the view for the first time, fields are not created, only when I click a button (#add_field). In this case there would be several lines with the same fields, understood?

  • Okay, and $('#id_item').change(function (e) { works for 1 field, but not for the right next?

  • not.... I was able to search for lots of the item just by writing the line where it would be. Now, when I added the function to add lines with jquery I couldn’t even do it for the primaire

2 answers

2


What’s the matter?

There are two problems in the code:

One of them is $('#id_item') does not run because the '#id_item' didn’t exist when that code ran, you have to use delegation of events.

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

How to solve:

Since you cannot use duplicate Ids I suggest you change everything that is ID (in this line HTML code) to classes, or by removing Ids and using name (as I did in the example).

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 the events.

So your code would be jQuery:

$('#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"
  • 1

    You did well. Now it’s working.. Thank you very much.

0

You will only get user the event in something created after, if it starts like this:

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

Detail that ids do not duplicate, use classname.

Browser other questions tagged

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