Hello!

The question is ...

How can I automatically change the id and label for input?

for example

 <input type="radio" id="id1"> <label for="id1"></label> <input type="radio" id="id2"> <label for="id2"></label> 

Please note that input is not inside a label, if that matters

  • four
    What do you mean by "automatic"? - Crantisz
  • I suppose they meant to auto-link them to each other - webDev_
  • Well, so what's the problem, it is not clear. take and change) only for the label, write not the input label (or label input), but input next ....... but it is generally not clear what you want to change, how and for what - Alexey Shimansky
  • It is necessary for me that each subsequent input has a unique id, for example, a number is appended at the end. - Alexey Yarygin
  • So take the number of inputs (length), add one to the value and write to the id attribute of the created input. problems are not clear again - Alexey Shimansky

2 answers 2

 $('#add-field').on('click', function(){ var nextId = $('input[type=checkbox]').length + 1; $('#wrapper').append('<input type="checkbox" id="id' + (nextId) + '"><label for="id' + nextId + '">Checkbox ' + nextId + '</label>'); }); 
 label:after { content: ''; display: block; margin-top: 10px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="wrapper"> <input type="checkbox" id="id1"> <label for="id1">Checkbox 1</label> <input type="checkbox" id="id2"> <label for="id2">Checkbox 2</label> </div> <button id="add-field">Добавить</button> 

  • Thank you very much! Very much help out! - Alexey Yarygin

It is rather strange, it is better to generate normal ID right away, but ...

 Array.from(document.querySelectorAll('label[for]')).forEach(l => { let id = l.getAttribute('for'), inp = document.querySelector(`#${id}`), newID = id + '1'; // Главное - не генерируйте для ВСЕХ элементов один ID; один раунд - один ID if(inp) l.setAttribute('for', newID), inp.setAttribute('id', newID); }); 
 <input type="checkbox" id="id1"> <label for="id1">Checkbox 1</label> <input type="checkbox" id="id2"> <label for="id2">Checkbox 2</label> 

  • I inserted your code, but nothing happened)) - Alexey Yarygin
  • @ Alexey Yarygin, how did he put it in? You understand that this is an example, not a solution for "copy-paste"? In the snippet works. - user207618