2

I am trying to create a design in which I need to create a form row with a delete button dynamically.

Basic requirements-

  1. Each row has a select dropdown which is populated from a static array on the addition of the row.
  2. All the dropdowns have the same set of options.
  3. Each row has a delete button on the click it removes the whole row

Design

Design

Current Implementation

HTML

<div id="ec-loanTypeContainer">
    <div id="ec-add-loan-wrapper">
        <div class="row select-row ec-border">
            <div id="ec-loan-type" class="col-md-4 mb-5 mb-md-0">
                <p class="ec-loan-type-label">Loan Type</p>
                <select class="form-select form-control ec-loan-type" id="ec-loan-type-dropdown"
                                aria-label="Default select example">
                    <option class="ec-option-placeholder" value="" disabled selected>Select Loan Type
                                </option>
                </select>
            </div>
            <div class="col-md-4">
                <p>Monthly Installment (SGD)</p>
                <div class="form-group mt-2">
                    <input type="text" class="ec-form-control" id="ec-monthly-installment"
                                  aria-describedby="emailHelp" placeholder="E.g. 12,345.00" />
                </div>
            </div>
            <div class="col-md-4">
                <p>Outstanding Amount (SGD) </p>
                <div class="form-group mt-2">
                    <input type="text" class="ec-form-control" id="ec-outstanding-amount"
                                  aria-describedby="emailHelp" placeholder="E.g. 12,345.00" />
                </div>
            </div>
        </div>
    </div>

Javascript/Jquery

const optionItems = [{
    value: "EX1",
    text: "Example1"
}, {
    value: "EX2",
    text: "Example2"
}, {
    value: "EX3",
    text: "Example3"
}]

//Append a row of select and input on click of add button
$('#ec-add-another-loan').on("click", function() {
    if (count <= 10) {
        $('#ec-add-loan-wrapper').append('<div class="row ec-select-row ec-border"><div class="col-md-4 mb-5 mb-md-0"><select name="ec-loan-type[]" class="form-select form-control ec-loan-type" aria-label="Default select example"><option class="ec-option-placeholder" value="" disabled selected>Select Loan Type</option></select></div><div class="col-md-4"><div class="form-group mt-2"><input type="text" name="ec-monthly-installment[]" class="ec-form-control" aria-describedby="emailHelp" placeholder="E.g. 12,345.00" /></div></div><div class="col-md-4"><div class="form-group mt-2 ec-outstanding-amount-container"><input type="text" class="ec-form-control" aria-describedby="emailHelp" placeholder="E.g. 12,345.00" /><img src="../iwov-resources/assets/icons/icon-delete.svg"  class="redTip img-fluid ec-delete-icon"/></div></div> </div > ')
        count++;
    }

    //Append options dynamically
    $.each(optionItems, function(i, item) {
        $("select[name=ec-loan-type[" + count + "]]").append($('<option>', {
            value: item.value,
            text: item.text,
        }));
    });
});

//Delete the row on click of the delete icon
$('.ec-delete-icon').click(function() {
    console.log("fsfssfsf", this)
    $(this).parent().remove();
});

Current issues with the code

  1. Unable to figure out how to populate the select dropdown dynamically
  2. Unable to figure out how to find the delete icon for the specific row and delete the row.

Would be great if someone can help with this.

Harsh Nagalla
  • 1,198
  • 5
  • 14
  • 26
  • Need more specific details about what is required for the dynamic select. Will they all be the same options? Do you have an ajax endpoint set up on server and if so what data format does it return? If not what is the data source? – charlietfl Apr 05 '21 at 03:14
  • @charlietfl apologies for not providing that information- it's a static array with 3 values just need to populate on addition of row – Harsh Nagalla Apr 05 '21 at 04:27
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Heretic Monkey Apr 05 '21 at 13:55

2 Answers2

3

The delete icon event listener should be delegated to a higher level element that will always exist. Your current version will only work for the ones that exist when that code runs but doesn't account for future ones added to the DOM

In addition the parent() isn't high enough in the tree...use closest() to go all the way up to the row

$('#ec-add-loan-wrapper').on('click', '.ec-delete-icon', function(){
     $(this).closest('.row').remove();
});

Understanding Event Delegation

charlietfl
  • 170,828
  • 13
  • 121
  • 150
1

Was able to make dynamic append work by getting all the select by name and then appending the options to the last index of select array on each add row click.

    //Append a row of select and input on click of add button
    $('#ec-add-another-loan').on("click", function() {
        if (count < 10) {
            $('#ec-add-loan-wrapper').append('<div class="row ec-select-row ec-border"><div class="col-md-4 mb-5 mb-md-0"><select name="ec-loan-type" class="form-select form-control ec-loan-type" aria-label="Default select example"><option class="ec-option-placeholder" value="" disabled selected>Select Loan Type</option></select></div><div class="col-md-4"><div class="form-group mt-2"><input type="text" name="ec-monthly-installment[]" class="ec-form-control" aria-describedby="emailHelp" placeholder="E.g. 12,345.00" /></div></div><div class="col-md-4"><div class="form-group mt-2 ec-outstanding-amount-container"><input type="text" class="ec-form-control" aria-describedby="emailHelp" placeholder="E.g. 12,345.00" /><img src="../iwov-resources/assets/icons/icon-delete.svg"  class="redTip img-fluid ec-delete-icon"/></div></div> </div > ')
            count++;
        }


        const selectIndex = $("select[name='ec-loan-type']").length - 1;
        let currentSelect = $("select[name='ec-loan-type']")[selectIndex];


        $.each(optionItems, function(i, item) {
            var option = $("<option value = " + item.value + ">" + item.text + "</option>")[0];
            currentSelect.append(option);
        });



        values = $("select[name='ec-loan-type']")
            .map(function() {
                return $(this).val();
            }).get();
        console.log("addaadad", values)
        return false;
    });
Harsh Nagalla
  • 1,198
  • 5
  • 14
  • 26