Increment numbers to ID name

Asked

Viewed 308 times

3

Good afternoon guys, I need a help, I have the following condition, after clicking a button I must insert a new checkbox and the first of these checkbox has an id="0", the following must have id="1", id="2", so successively, 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"
});
  • Purely numerical id’s are not very good practice, so much so that in previous versions of html were not valid.

2 answers

4


Have some div to manipulate that it will become easy. Create a variable to always add one id new. In my case, I used the i; Within the function of click of the button you will use, add the .append to the div receiver 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>
  • It would be more interesting to post a reply commenting on what each feature does.

  • Thank you Diego!

  • @Leandrade, I only created a variable to increment when adding a new element at the click of the button.

  • Arrange, @Munirbaarini! ;)

  • @Leandrade, done! See if you can understand... hug and good luck.

  • Jóia man, I just commented due to the fact that people who want to learn research something similar and have an easy way to understand, how is being done that.

Show 1 more comment

3

Simple, first you will need to put the inputs in a div, then create a counter variable, I declared it as cont, after, capture the event click, and giving a append of the element in div maid.

To finish, just increment the counter.

Upshot:

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>

  • Expensive downvote, could you tell me where I went wrong? I would like to understand so I can fix.

  • It wasn’t my downvote, but I believe your answer is basically the same as the answer above that was posted earlier.

  • And so considered cópia? I was responding when I had no answer, just took a while to post

  • Yeah, I guess that’s no reason to downvote.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.