Wrapping input and label field with an li

Viewed 86

I am dynamically creating a label and input inside a ul. I need to wrap the label and input inside an li. I've tried wrap, append, appenTo, and before. I can't figure it out. Here is the code.

const departments = $('#departments ul');

for (let i = 0; i < len; i++) {
                let num = response[i][0];
                let description = response[i][1];


                $('<input />', {type: 'checkbox', id: +num, value: description}).appendTo(departments);
                $('<label />', {'for': +num, text: description}).appendTo(departments);

            }
1 Answers

To achieve this you need to create the new li element, append that to the ul, then append the new input and label to the li. Try this:

const $departments = $('#departments ul');
const len = 5;

for (let i = 0; i < len; i++) {
  let num = i; // response[i][0]; // for testing only
  let description = 'Label ' + i; // response[i][1]; // for testing only

  var $li = $('<li />').appendTo($departments);
  $('<input />', {
    type: 'checkbox',
    id: +num,
    value: description
  }).appendTo($li);
  $('<label />', {
    for: +num,
    text: description
  }).appendTo($li);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="departments">
  <ul></ul>
</div>

Related