Search code examples
jqueryformsasp.net-coreintl-tel-input

Cannot change country of intl-tel-input when clone ASP.NET Core form


I have form in view ASP.NET Core, and use intl-tel-input jQuery plugin and this contact form can select country code and enter phone or fax number when click on add another contact clone form to another one when it cloned I cannot change the select country's of cloned form and need to get full number and country code for every form

My attempt - view:

<div id="contact-forms-container">
    <!--Contact Form-->
    <div class="form-card contact-form-card">
        <form>
            <div class="form-row align-items-center">
                <div class="col-md-6 mb-3">
                    <label for="">Phone number</label>
                    <input type="text" class="form-control contact-phone" id="contact-phone" placeholder="Phone number">
                </div>
                <div class="col-md-6 mb-3">
                    <label for="">Fax</label>
                    <input type="text" class="form-control fax-contact" id="fax-contact" placeholder="Fax">
                </div>
            </div>
        </form>
    </div>
</div>

JS

$(document).ready(function () {
    var contactCounter = 2;

    // Initialize the first form
    initializeForm($(".contact-form-card"));

    $("#add-another-contact-form").on("click", function () {
        const clonedForm = cloneForm($(".contact-form-card"));
        initializeForm(clonedForm);
        $("#contact-forms-container").append(clonedForm);
        contactCounter++;
    });

    // Function to clone a form
    function cloneForm(originalForm) {
        const clonedForm = originalForm.clone();

        const formTitle = clonedForm.find(".form-title");
        formTitle.text(`Contact ${contactCounter}`);

        const removeButton = clonedForm.find(".remove-form-button");
        removeButton.on("click", function () {
            clonedForm.remove();
        });

        return clonedForm;
    }

    // Function to initialize a form
    function initializeForm(form) {
        const phoneInput = form.find(".form-control.contact-phone");
        const faxInput = form.find(".form-control.fax-contact"); 

        console.log('Check if the phoneInput element is correctly selected')
        console.log(phoneInput); 
        console.log(faxInput);  

        // Destroy previous instances if any
        phoneInput.intlTelInput("destroy");
        faxInput.intlTelInput("destroy");

        // Initialize IntlTelInput for phone and fax inputs
        var itiContact = window.intlTelInput(phoneInput[0], {
            formatOnDisplay: true,
            separateDialCode: true,
            hiddenInput: "full_number",
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
        });

        var itiFax = window.intlTelInput(faxInput[0], {
            formatOnDisplay: true,
            separateDialCode: true,
            hiddenInput: "full_number",
            utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
        });

        // Store the instances in the element's data for later access
        phoneInput.data("itiContact", itiContact);
        faxInput.data("itiFax", itiFax);

        itiContact.promise.then(function () {
            phoneInput.trigger("countrychange");
        });

        itiFax.promise.then(function () {
            faxInput.trigger("countrychange");
        });

        phoneInput.on("countrychange", function (event) {
            var selectedCountryData = phoneInput.data("itiContact").getSelectedCountryData();
            console.log(selectedCountryData);
        });

        faxInput.on("countrychange", function (event) {
            var selectedCountryData = faxInput.data("itiFax").getSelectedCountryData();
            console.log(selectedCountryData);
        });
    }
});

Solution

  • When the document is ready, you can clone the contact form card, at this time, since you didn't select the country, so they will use the default country. We can use it as initial card. Then, after clicking the add card button, you can append the previous cloned card (initial card) to the container and use JQuery to get the last card (which is the initial card).

    After modified, the code like this:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/build/css/intlTelInput.css">
     
    <input type="button" id="add-another-contact-form" class="btn btn-primary" value="AddForm" />
    <div id="contact-forms-container">
        <!--Contact Form-->
        <div class="form-card contact-form-card">
            <form>
                <div class="form-row align-items-center">
                    <div class="col-md-6 mb-3">
                        <label for="">Phone number</label>
                        <input type="text" class="form-control contact-phone" id="contact-phone" placeholder="Phone number">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label for="">Fax</label>
                        <input type="text" class="form-control fax-contact" id="fax-contact" placeholder="Fax">
                    </div>
                </div>
            </form>
        </div>
    </div>
    

    JS scripts:

    @section Scripts{
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/js/intlTelInput.min.js"></script> 
        <script>
            $(document).ready(function () {
                var contactCounter = 2;
                //clone the first card, use it as the initial card.
                var clonedForm = cloneForm($(".contact-form-card:first")); 
                // Initialize the first form
                initializeForm($(".contact-form-card"));
    
                $("#add-another-contact-form").on("click", function () { 
                    var newform = clonedForm;
                    $("#contact-forms-container").append(newform);
                    //clone the last card, as the initial card.
                    clonedForm = cloneForm($(".contact-form-card:last"));
                    initializeForm(newform);
                    contactCounter++;
                });
    
                // Function to clone a form
                function cloneForm(originalForm) {
                    const clonedForm = originalForm.clone();
    
                    const formTitle = clonedForm.find(".form-title");
                    formTitle.text(`Contact ${contactCounter}`);
    
                    const removeButton = clonedForm.find(".remove-form-button");
                    removeButton.on("click", function () {
                        clonedForm.remove();
                    });
    
                    return clonedForm;
                }
    
    
                // Function to initialize a form
                function initializeForm(form) {
                    const phoneInput = form.find(".form-control.contact-phone");
                    const faxInput = form.find(".form-control.fax-contact");
    
                    console.log('Check if the phoneInput element is correctly selected')
                    console.log(phoneInput);
                    console.log(faxInput);
    
                    ////// Destroy previous instances if any
                    //phoneInput.intlTelInput("destroy");
                    //faxInput.intlTelInput("destroy");
    
                    var precontact = intlTelInput(phoneInput[0]).destroy();
                    var prefax = intlTelInput(faxInput[0]).destroy();
    
                    // Initialize IntlTelInput for phone and fax inputs
                    var itiContact = window.intlTelInput(phoneInput[0], { 
                        formatOnDisplay: true,
                        separateDialCode: true,
                        hiddenInput: "full_number",
                        utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
                    }); 
                    var itiFax = window.intlTelInput(faxInput[0], {
                        formatOnDisplay: true, 
                        separateDialCode: true,
                        hiddenInput: "full_number",
                        utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"
                    });
    
                    // Store the instances in the element's data for later access
                    phoneInput.data("itiContact", itiContact);
                    faxInput.data("itiFax", itiFax);
    
                    itiContact.promise.then(function () {
                        phoneInput.trigger("countrychange");
                    });
    
                    itiFax.promise.then(function () {
                        faxInput.trigger("countrychange");
                    });
    
                    phoneInput.on("countrychange", function (event) {
                        var selectedCountryData = phoneInput.data("itiContact").getSelectedCountryData();
                        console.log(selectedCountryData);
                    });
    
                    faxInput.on("countrychange", function (event) {
                        var selectedCountryData = faxInput.data("itiFax").getSelectedCountryData();
                        console.log(selectedCountryData);
                    });
                }
            });
        </script>
    }
    

    The output like this: enter image description here