0

My goal is to convert a select (multiple) into an unordered list using jquery. To do so, I thought I could use a piece of code from this thread: https://stackoverflow.com/a/7336612/10132321

I'm trying to convert the select with id "mylist" into an ul. After running the js, the first listbox should look like the second one with checkboxes but nothing happens. Am I doing something wrong?

https://jsfiddle.net/tomsx/t307vebr/

$(function() {
  var id = "mylist";
  $('#' + id).after("<ul id='mylist2' />")
    .children("option").each(function() {
      $("#mylist2").append("<li>" + $(this).text() + "</li>");
    })
    .end().remove();
  $('#mylist2').attr("id", id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="mylist" multiple size="6">
  <option value="0">First</option>
  <option value="1">Second</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
  <option value="5">Fifth</option>
</select>
freedomn-m
  • 24,983
  • 7
  • 32
  • 55
smolo
  • 366
  • 7
  • 21
  • 1
    Converted your code to a snippet - it appears to be working fine. Any other "it should" hasn't been attempted in the code (looks like a direct copy+paste) from the linked answer). What changes have you attempted to the existing code? Code must be in the question, not linked on jsfiddle. – freedomn-m Feb 07 '19 at 16:04
  • Your fiddle is missing jquery - adding that just does the same as here - converts the `select` to a `ul` – freedomn-m Feb 07 '19 at 16:06
  • 1
    What you're doing wrong is appending `
  • text
  • ` instead of `
  • text
  • ` – freedomn-m Feb 07 '19 at 16:07
  • I must be mi-understanding the question. The code appears to do what you are describing, should it be making a `list-box` of selectable options instead? – Steve0 Feb 07 '19 at 16:07
  • Jquery added in my fiddle. The Javascript is supposed to turn the select with id "mylist" in into a listbox with checkboxes. (the first select should then look like the second one in the fiddle) – smolo Feb 07 '19 at 16:12
  • @freedomn-m, the second paragraph of the question seems to conflict between it's two sentences. Is @toms trying to make a `ul` (like the code posted does) or a `list-box` of `check-boxes` – Steve0 Feb 07 '19 at 16:12
  • 1
    @Steve0 I think they key is in the fiddle - it looks like OP has created an "expected result" "*the first listbox should look like the second one with checkboxes*". They're not real list-boxes, just styled ULs – freedomn-m Feb 07 '19 at 16:16