Home » Jquery » javascript – how to append an existing form with select form fields using jQuery

javascript – how to append an existing form with select form fields using jQuery

Posted by: admin February 22, 2020 Leave a comment

Questions:

Given some html, a form named inputPrefixListIx and a button named addPrefixListIx

<div id="divinputPrefixListIx" name="divinputPrefixListIx">
    <form name="inputPrefixListIx" class="inputPrefixListIx">
        <div class="row">

                <div class="col-12">
                    <select name="spec" class="mdb-select md-form colorful-select dropdown-primary">
                        <option value="" disabled selected>spec</option>
                        <option value="replace" data-secondary-text="">replace</option>
                        <option value="delete" data-secondary-text="">delete</option>
                    </select>
                    <label class="mdb-main-label">spec</label>
                </div>

            </div>

        </div>
        <br><br><br>
    </form>

    <div class="col-12">
        <button type="button" name="addPrefixListIx" id="addPrefixListIx" class="btn btn-block btn-flat"><i class="fas fa-plus"></i></button>
    </div>

</div>

I would like to clone/duplicate the form when the user clicks on the addPrefixListIx button using jQuery I guess.

The jQuery used (and works partially) looks like this:

<script type="text/javascript" src="/static/js/blueprints.js"></script>

jQuery(($) => {

    // PrefixListIx
    $('#addPrefixListIx').click(function() {
        $('.inputPrefixListIx:first').clone().insertAfter('.inputPrefixListIx:last');
    });
    if (sessionStorage.getItem('PrefixListIx') !== null) {
        $('#divinputPrefixListIx').addClass('d-none');
    }
    else {
        $('#divmanifestPrefixListIx').addClass('d-none');
    }
    $('#delPrefixListIx').click(function() {
        sessionStorage.removeItem('PrefixListIx');
        $('#divinputPrefixListIx').toggleClass('d-none');
        $('#divmanifestPrefixListIx').toggleClass('d-none');
    });

});

What doesn’t work is that the options of the select form fields do not appear.

Would you be so kind to advise what I am doing wrong and how to fix this ?

EDIT: I encountered this Clone isn't cloning select values which suggests a fix available here https://github.com/spencertipping/jquery.fix.clone but I don’t know how to use it given the provided example, can somebody please advise ?

How to&Answer: