Jibeji
Jibeji

Reputation: 473

Change id of multiple dynamic fields

I have a form with dynamic fields but I would like the additional fields to have a different ID.

My code works pretty well but as it is a simple copy of HTML code, there is no reference of any ID. I am a totally beginner in Javascript, and I don't know how to achieve that.

$(".addMore").click(function() {
  if ($('body').find('.field').length <= 10) {
    var fieldHTML = '<div class="form-group field">' + $(".fieldCopy").html() + '</div>';
    $('body').find('.field:last').after(fieldHTML);
  }
});

// Remove
$("body").on("click", ".remove", function() {
  $(this).parents(".field").remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="">
  <div class="form-group field">
    <div class="input-group">
      <input id="name" type="text" name="name[]" class="form-control" />
      <input id="email" type="text" name="email[]" class="form-control" />
      <div class="input-group-addon">
        <a href="javascript:void(0)" class="btn btn-success addMore">Add</a>
      </div>
    </div>
  </div>
  <input type="submit" name="submit" class="btn btn-primary" value="Submit" />
</form>

<!-- copy of input fields group -->
<div class="form-group fieldCopy" style="display: none;">
  <div class="input-group">
    <input id="name" type="text" name="name[]" class="form-control" />
    <input id="email" type="text" name="email[]" class="form-control" />
    <div class="input-group-addon">
      <a href="javascript:void(0)" class="btn btn-danger remove">Remove</a>
    </div>
  </div>
</div>

Upvotes: 0

Views: 253

Answers (1)

Stefan Avramovic
Stefan Avramovic

Reputation: 1353

You can set it like this:

var i = 0;
    $(".addMore").click(function() {
      if ($('body').find('.field').length <= 10) {
        var fieldHTML = '<div class="form-group field">' + $(".fieldCopy").html() + '</div>';
        $('body').find('.field:last').after(fieldHTML);
           $('body').find('.field:last').attr("id",i);
        i++
      }
    });

Upvotes: 1

Related Questions