screwtape_mk
1 month ago

Dynamically add/remove text fields in a form

Posted 1 month ago by screwtape_mk

I am trying to create a form that allows a user to enter a series of emails by dynamically adding a new text field. I have followed this implementation of here which works well.: https://stackoverflow.com/questions/34748659/dynamically-add-and-remove-textboxes-and-get-value-of-dynamic-textbox-using-jque

The one change i made which suddenly make the "remove" button not work is adding a label between the input fields as below:

jQuery(document).ready( function () {

        $("#append").click( function(e) {
          e.preventDefault();
          
          
          var urlParams = new URLSearchParams(window.location.search);
          var domain = urlParams.get('domain');
          //console.log(domain);
         
         // document.getElementById('domain').innerHTML = domain;
          
        $(".inc").append(`<div class="controls">\
                <input class="form-control" type="text" id="email" name="email">\
                <labe>@</label>\
                <input class="form-control" type="text" id="domain" name="domain">\
                <a href="#" class="remove_this btn btn-danger">remove</a>\
                <br>\
                <br>\
                <br>\
            </div>`
           
            );
        return false;
        });

    jQuery(document).on('click', '.remove_this', function() {
        jQuery(this).parent().remove();
        return false;
        });
    $("input[type=submit]").click(function(e) {
      e.preventDefault();
      $(this).next("[name=textbox]")
      .val(
        $.map($(".inc :text"), function(el) {
          return el.value
        }).join(",\n")
      )
    })
    
    
  });
  

The problem is the "remove" button now only removes :

<labe>@</label>\
                <input class="form-control" type="text" id="domain" name="domain">\

while leaving the first text box:

<input class="form-control" type="text" id="email" name="email">\

Please sign in or create an account to participate in this conversation.