Increase numbers to ID name

3

Good afternoon, I need a help, I have the following condition, after clicking a button I must insert a new checkbox and the first of these checkboxes has an id="0", the next one must have id="1" id="2", so on, always after clicking the button that inserts a new checkbox. Example:

HTML

<input type="checkbox" id="0">

JS

$(document).on('click','.add',function(){
  //acrescentar novo checkbox com id="1"
  //acrescentar novo checkbox com id="2"
});
    
asked by anonymous 04.10.2018 / 20:52

2 answers

4

Have some div to handle this will be easy. Create a variable to always add a new id . In my case, I used i ; Within the click function of the button you will use, add the event of .append to the div fault of the new element, according to the code below:

var i = 0;    
$('.buttonQueClicou').on('click', function() {
    $('.divParaManipular').append('<input type="checkbox" id="'+i+'" />');
    i++;
});

<button value="add" class="buttonQueClicou" />    
<div class="divParaManipular">
<!-- SEUS CHECKBOX ENTRARÃO AQUI -->
</div>
    
04.10.2018 / 20:59
3

Simple, you first need to put the inputs in a div , then create a counter variable, declare it as cont , then, it captures the event click , and it gives a append of the element in div created.

To finish, just increment the counter.

Result:

let cont = 1;
$('#btn-add').on('click',function(){
    $('.checks').append('<input type="checkbox" id="'+cont+'">')
    cont++;
});
<div class="checks">
  <input type="checkbox" id="0">
</div>
<button id="btn-add"> Adicionar </button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
04.10.2018 / 21:05