2

I want to allow users to dynamically create as many input fields as they want within the format that I supply to them. I need the features below:

  • There should be a button to add more fields
  • There should be a button next to each field to delete the field

Is there any method which satisfies my needs?

I've already used the append() method in JavaScript but I was not able to delete the fields using a button next to it.

onclick on a button:

$( '#some_div' ).append( '<input type="text" name="tel[]" class="form-control">' );

I've heard something about grids but could not find anything relevant.

Alireza A2F
  • 519
  • 4
  • 26

1 Answers1

1

append() will work for adding fields. To subtract fields you could use remove().

One possible method of performing this action is done by wrapping the field and the delete button in a div, making it easy to target the entire group for deletion. jQuery's closest() finds the closest element up the DOM that matches your search, relative to the location you're searching from.

$("#add-field").click(function() {
  $("#some_div").append('<div class="input-block"><input type="text" name="tel[]" class="form-control"><input type="button" class="remove-field" value="-"></div>');
});

$(document).on("click", ".remove-field", function() {
  $(this).closest(".input-block").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="button" id="add-field" value="+ Add Field">
<div id="some_div"></div>
Grant Noe
  • 985
  • 8
  • 29
  • 1
    The String within the `append()` method needs to be compressed in one row so that JavaScript recognizes that as one single String. Is there any way that the String which contains HTML tags be in multiple rows so that it is more readable? – Alireza A2F Jun 19 '19 at 17:03
  • 1
    The answer is "yes," but depending upon your desires for browser support, the answer is "kind of." When I write apps for my company, I use "javascript template literals" for my stringed html. This allows me to go multi-line, and even include inline variables with no issue. https://stackoverflow.com/questions/805107/creating-multiline-strings-in-javascript The problem is the browser support. If you need to support IE or some Edge cases, I'd avoid it. https://caniuse.com/#feat=template-literals – Grant Noe Jun 19 '19 at 17:06
  • 1
    TnQ it was really helpful. – Alireza A2F Jun 19 '19 at 17:11