jQuery - How to wrap input tag with label

Refresh

April 2019

Views

19 time

1

I would like to wrap input tag with label and li tag.

<li><label><input type="checkbox" value="1">Apple</label></li>
<li><label><input type="checkbox" value="2">Banana</label></li>
<li><label><input type="checkbox" value="3">Orange</label></li>

However, Output is following...

<li><label><input type="checkbox" value="1">Apple</input></label></li>
<li><label><input type="checkbox" value="2">Banana</input></label></li>
<li><label><input type="checkbox" value="3">Orange</input></label></li>

I can't remove </input>

My code:

var foods = [{id:1, name:'Apple'},{id:2, name:'Banana'},{id:3, name:'Orange'}];

for(var f in foods) {
  var tag_input = $('<input type="checkbox">');
      tag_li = $('<li>')
      tag_label = $('<label>');
  tag_input.val(foods[f]['id']);
  tag_input.text(foods[f]['name']);

  var tag = tag_li.append(tag_label.append(tag_input))
  console.log(tag[0].outerHTML);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1 answers

1

One option is to construct a string of HTML like:

var foods = [{id:1, name:'Apple'},{id:2, name:'Banana'},{id:3, name:'Orange'}];
var html = "";

foods.forEach(function(o) {
  html += '<li><label><input type="checkbox" value="' + o.id + '">' + o.name + '</label></li>';
});

console.log(html);