Джанго Пользовательский Formset Javascript

В форме счета, которую я подготовил с Django, есть поле динамической формы. Я использовал javascript django formset для добавления динамической строки. Таким образом, я могу добавлять и удалять строки. Я делаю автозаполнение на одном из полей (поле = имя). Но скрипт автозаполнения не работает, когда я добавляю новую строку. Яваскрипты похожи на те, которые я отправляю ниже. Как работает автозаполнение при добавлении новой строки?

Javascript код Django FormSet:

    $(document).ready(function () {
    function updateElementIndex(el, prefix, ndx) {
        var id_regex = new RegExp('(' + prefix + '-\\d+-)');
        var replacement = prefix + '-' + ndx + '-';
        if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex,
        replacement));
        if (el.id) el.id = el.id.replace(id_regex, replacement);
        if (el.name) el.name = el.name.replace(id_regex, replacement);
    }

    function deleteForm(btn, prefix) {
        var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
        if (formCount > 1) {
            // Delete the item/form
            $(btn).parents('.item').remove();
            var forms = $('.item'); // Get all the forms
            // Update the total number of forms (1 less than before)
            $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
            var i = 0;
            // Go through the forms and set their indices, names and IDs
            for (formCount = forms.length; i < formCount; i++) {
                $(forms.get(i)).children().children().each(function () {
                    if ($(this).attr('type') == 'text') updateElementIndex(this, prefix, i);
                });
            }
        } // End if
        else {
            alert("You have to enter at least one todo item!");
        }
        return false;
    }

    function addForm(btn, prefix) {
        var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
        // You can only submit a maximum of 10 todo items
        if (formCount < 10) {
            // Clone a form (without event handlers) from the first form
            var row = $(".item:first").clone(false).get(0);
            // Insert it after the last form
            $(row).removeAttr('id').hide().insertAfter(".item:last").slideDown(300);

            // Remove the bits we don't want in the new row/form
            // e.g. error messages
            $(".errorlist", row).remove();
            $(row).children().removeClass("error");

            // Relabel or rename all the relevant bits
            $(row).children().children().each(function () {
                updateElementIndex(this, prefix, formCount);
                $(this).val("");
            });

            // Add an event handler for the delete item/form link
            $(row).find(".delete").click(function () {
                return deleteForm(this, prefix);
            });
            // Update the total form count
            $("#id_" + prefix + "-TOTAL_FORMS").val(formCount + 1);
        } // End if
        else {
            alert("Sorry, you can only enter a maximum of ten items.");
        }
        return false;
    }
    // Register the click event handlers
    $("#add").click(function () {
        return addForm(this, "form");
    });

    $(".delete").click(function () {
        return deleteForm(this, "form");
    });
});

Мой скрипт автокомпиляции

// Define variables
var lookupSelector = '.urun'; // The ID selector to use for the autocomplete function
var lookupInput = $(lookupSelector);

var itemQtyPriceSelectors = '#itemQty, #vergiler_haric_satis_fiyati'; // The ID's used for the Price and Qty binding for updating price
var filePath;

/*
 First, set the path to fetch items from database
 Initialize the lookup for the first input on the page
 */
mioInvoice.setPathValue('/panel/stok/urunler/listesi/');
mioInvoice.fetchItems(lookupInput);

var mioInvoice = {

    /**
     * Fetch items from database using autocomplete method
     * @param $lookupInput - Input selector
     */
    fetchItems: function ($lookupInput) {

        // apply autocomplete method to newly created row
        $lookupInput.autocomplete({
            source: window.filePath,
            minLength: 1,
            select: function (event, ui) {

                var $itemRow = $(this).closest('tr');

                // Modify this information to match the information coming from assets/ajax-services/fetch-inventory.php
                $itemRow.find('.urun').val(ui.item.name);
                $itemRow.find('.birim_fiyati').val(ui.item.vergiler_haric_satis_fiyati);

                // Give focus to the next input field to receive input from user
                $itemRow.find('#itemQty').focus();
                return false;
            }
        });

    },

0 ответов

Другие вопросы по тегам