What I want is, I want to generate a new input type = text
whenever a plus icon is getting clicked. SO I have written below code for the same.
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
alert(numItems);
if (numItems != 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.substr(13, lastfieldsid.length));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata1" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata1" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'></i></div></td></tr>"
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
</div>
3
Answers
Assuming that you are going to add new input field in div#dvDVRdata1. You need to append the HTMLcontent to that
div
as following:$('#dvDVRdata1').append(tr);
The thing is you need to
append
the element, which you did not do in the code in your question.As for remove, you also have not done it in your question yet. Here’s the example of add and remove.
Couple of problem in your code.
slice(-1)
to get last character of id. It’s remove your dependency using hardcodesubstr(13,...
and you can use that value to increase new generated id by +1 .input
using$('.form-group').find('input').length < 5
which check the length of input insideform-group
class and user only able to add 5 inputs.form-group
class using$('.form-group').append(tr);
.tr
usingminus
class.Example: