Umair Qazi Umair Qazi - 4 months ago 10
jQuery Question

I am adding a textfield dynamically via jQuery and id of text field is not incrementing

I am copying a textfield but its id is not increment. Is there any other way to create a specific id after copying a textfield



$(function(){
$('#idbtn').click(function(){
$('#Institute').clone().attr('id','Institute_' + $(this).index()).insertAfter('#Institute');
});//click
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="Institute">
<input type="button" id="idbtn" value="add"/>




Answer

Keep a separate variable and increment that each time the function is called. jQuery's .index() is a DOM search, not what you want at all.

  $(function() {
    var i = 0; // inside the closure
    $('#idbtn').click(function() {
      $('#Institute').clone().attr('id', 'Institute_' + ++i).insertAfter('#Institute');
    })
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <div id="Institute">DIV</div>

<button id="idbtn">click me</button>

Comments