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>
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++
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.