1

I created a simple multi-text input with jQuery, appending text fields working fine. But, struggling to remove them. I googled, checked past questions but, don't know how to match them to my code.

Here is my code

$(document).ready(function () {
    var i = 1;
    (function () {
        $('.dd').on('click', '.addRow', function () {
            i = i+1;
            var start = $('#fields'),
            newRow = $('<input type="text" name="i" class="quantity" /><p class="xx">X</p><br><br>');
            $(start).append(newRow);
        });
    })();
});

HTML

<div class="dd">
    <form action="js-more-fields.php" method="get">
        <div id="fields">
        </div>
        <p class="addRow">Add a Row</p>
        <input type="submit" id="submit" />
    </form>
</div>
Tharindu Thisarasinghe
  • 3,486
  • 7
  • 32
  • 67

2 Answers2

4

Here is working fiddle

 $(document).ready(function () {
    var i = 1;
    (function () {
        $('.dd').on('click', '.addRow', function () {
            i = i+1;
            var start = $('#fields'),
                newRow = $('<div id='+i+'><input type="text" name="i" class="quantity"/><span class="delete">X</span></div><br/>');
            $(start).append(newRow);
        });
        $('body').on('click', '.delete', function(e) {
        $(this).parent().remove();
       });


    })();
    });

:You are trying to bind click on dynamic created element which does not exist.You can use delegate or on for doing this.

Rajan Singh
  • 611
  • 4
  • 9
1

Use JQuery on for dynamically created elements:

api.jquery.com

ρяσѕρєя K
  • 130,641
  • 51
  • 193
  • 212
Muhammad Atif
  • 1,020
  • 9
  • 20