dwadwa

mail@pastecode.io avatar
unknown
html
2 years ago
2.3 kB
2
Indexable
Never
 <div data-toggle="fieldset" id="product-fieldset">{{ form.products.label }} &nbsp;<button type="button" data-toggle="fieldset-add-row" data-target="#product-fieldset">Add new line</button>
 <table>
                <tr>
                    <th>Product</th>
                    <th>SKU</th>
                    <th>Amount</th>
                    <th></th>
                </tr>
  {% for product in form.products %}
                <tr data-toggle="fieldset-entry">
                    <td>{{ product.product }}</td>
                    <td>{{ product.SKU }}</td>
                    <td>{{ product.Amount }}</td>
                    <td><button type="button" data-toggle="fieldset-remove-row" id="product-{{loop.index0}}-remove">-</button></td>
                </tr>
    {% endfor %}</table></div>
<script src="{{ url_for("static", filename="js/jquery-1.10.2.min.js") }}"></script>
<script src="{{ url_for("static", filename="js/page.js") }}"></script>

page.js:
$(function() {
    $("div[data-toggle=fieldset]").each(function() {
        var $this = $(this);

            //Add new entry
        $this.find("button[data-toggle=fieldset-add-row]").click(function() {
            var target = $($(this).data("target"))
            console.log(target);
            var oldrow = target.find("div[data-toggle=fieldset-entry]:last");
            var row = oldrow.clone(true, true);
            console.log(row.find(":input")[0]);
            var elem_id = row.find(":input")[0].id;
            var elem_num = parseInt(elem_id.replace(/.*-(\d{1,4})-.*/m, '$1')) + 1;
            row.attr('data-id', elem_num);
            row.find(":input").each(function() {
                console.log(this);
                var id = $(this).attr('id').replace('-' + (elem_num - 1) + '-', '-' + (elem_num) + '-');
                $(this).attr('name', id).attr('id', id).val('').removeAttr("checked");
            });
            oldrow.after(row);
        }); //End add new entry

                //Remove row
        $this.find("button[data-toggle=fieldset-remove-row]").click(function() {
            if($this.find("div[data-toggle=fieldset-entry]").length > 1) {
                var thisRow = $(this).closest("div[data-toggle=fieldset-entry]");
                thisRow.remove();
            }
        }); //End remove row
    });
});