J.A.Manato
J.A.Manato

Reputation: 27

How can I add clone counter id in javascript

I don't know where to put the counter; The next cloned id must be gender_1

Example:

<select id="gender">

Next is:
`<select id="gender_1">`

then:
`<select id="gender_2">`

https://jsfiddle.net/f7hjh1gf/6/

Upvotes: 0

Views: 472

Answers (2)

prasanth
prasanth

Reputation: 22500

Try this, before append to the element you need to replace the cloned selected element id using find() function and update the id incremented using c++

Updated jsfiddle

$(document).ready(function(){
var c=1;
    $(document).on('click', '#mode', function(){
        $("#notok").clone(true).find('select').attr('id','gender_'+(c++) ).closest('.ok').appendTo("#clones");
    });
});

Upvotes: 2

Dij
Dij

Reputation: 9808

Everytime you add a clone get the number of clones already present and increment it by one before adding it to "gender_", you can use $("#clones div").length to get number of clones currently present.

$(document).ready(function(){
    $(document).on('click', '#mode', function(){
        $("#notok").clone(true).attr('id', "gender_"+($("#clones div").length + 1)).appendTo("#clones");
    });
});
<div class="container">

<div class="ok" id="notok">
	<select id="gender">
    	<option value="Male">Male</option>
        <option value="Female">Female</option>
    </select>

    
</div>

<div id=clones></div>

<button id="mode">Clone</button>


  

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">

  <!-- Modal content-->
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h4 class="modal-title">Modal Header</h4>
    </div>
    <div class="modal-body">
      <p>Some text in the modal.</p>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
    </div>
  </div>
  
</div>
  </div>
  
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Related Questions