0

Possible Duplicate:
How to convert <select> dropdown into an unordered list using jquery?

I want to convert all select dropdowns into ul lists for printing.

<select>
 <option>Item 1</option>
 <option>Item 2</option>
 <option>Item 3</option>
</select>

into:

<ul>
 <li>Item 1</li>
 <li>Item 2</li>
 <li>Item 3</li>
</ul>

Why does this only show?:

<ul></ul>

jquery:

$('select').parent().append('<ul></ul>');
$('select option').each(function(){
  $('<ul>').append('<li>'+$(this).text()+'</li>');
});

$('select').remove();

edit: removed select ID. I want to step through each and not just one particular select.

Community
  • 1
  • 1
simple
  • 2,277
  • 7
  • 34
  • 54

2 Answers2

2

You're creating a new ul element at every step in the loop. Use this instead:

var $select = $('#oberservationType'),
    $list = $('<ul />');

$select.find('option').each(function(){
    $list.append('<li>' + $(this).text() + '</li>');
});

$select.after( $list ).remove();

Here's the fiddle: http://jsfiddle.net/YDbgv/


To do this for every select on the page, use this:

$('select').each(function () {
    var $this = $(this),
        $list = $('<ul />');

    $this.find('option').each(function(){
        $list.append('<li>' + $(this).text() + '</li>');
    });

    $this.after( $list ).remove();
});

Here's the fiddle: http://jsfiddle.net/YDbgv/2/

Joseph Silber
  • 205,539
  • 55
  • 352
  • 286
  • I would like it to go through all select and not just #oberservationType. How would I step through each – simple Feb 01 '13 at 20:16
0

This should do. Please give it a try once.

$(function()
{
    var items = $('#oberservationType option'), str = '<ul>';
    for (var i = 0, len = items.length; i < len; i++)
    {
        str = str + '<li>'+items[i].innerHTML+'</li>';
    }
    str = str + '</ul>';
    console.log(str);
    $('<div/>').html(str).appendTo('body');
    $('#oberservationType').remove();

});
nicholasnet
  • 1,793
  • 2
  • 18
  • 36