views:

188

answers:

5

I am trying to clone a select list into a standard ul list for enhanced javascript select box manipulation/styling.

Basically, if I do this: $("#calendar select option").clone().appendTo("#test");

i get the following html

<ul id="test">
<option>All Types</option>
<option>Installation</option>
<option>Music</option>
<option>Performing Arts</option>
<option>Season</option>
<option>YUIYIYI</option>
</ul>

How can i then change all the <option> tags to be <li> tags without losing all the values?

Any help much appricated.

A.

A: 

instead of...

$("#calendar select option").clone().appendTo("#test");

try...

$("#calendar select option").each(function(){
  $("<li>" + $(this).text() + "</li>").appendTo("#test");
});

Short and sweet.

Ryan
Appending a bunch of times is rather slow.
KyleFarris
Probably true but given the sample size he posted I doubt it'd be a noticeable delay using multiple appends.
Ryan
A: 
$("#calendar select option").each(
    function(){
        html = $(this).html();
        e = document.createElement('li');
        e.setAttribute('innerHTML',html);
        $("#test").append(e);
    }
);

Not tested, but that should get you most of the way there. Good luck!

inkedmn
That is mighty un-jquery of you to use things like `document.createElement('li')`... Nothing wrong with it... just feels bad.
KyleFarris
Let's not forget that jQuery *is* javascript :) createElement is, in my opinion, the right tool for this particular task.
inkedmn
+1  A: 

Something like this should work:

var list_items = '';
$("#calendar select option").each(function() {
    var $this = $(this);
    list_items += '<li rel="'+$this.val()+'">'+$this.html()+'</li>';
});
$("#test").append($(list_items));

Just as a side note, from what I recall, string concatenation and one append is usually faster than a bunch of appends or array pushes.

Credit goes to @cballou for the rel tag part...

KyleFarris
+2  A: 

I would recommend you to get the right formed li elements markup by traversing your options.

An example using $.map:

var listItems = $("#calendar select option").map(function(){
  return '<li>' + $(this).text() + '</li>';
}).get().join("");

$("#test").append(listItems);

Check the above snippet here.

CMS
Great response. I really need to start utilizing the `map` method more.
KyleFarris
Great, thanks for everyones help. Works a charm....
Adi
+1  A: 

My opinion is that the option values should be treated as rel tags for your "custom select":

var listitems = [];
$("#calendar select option").each(function() {
    var $this = $(this);
    listitems.push('<li rel="' + $this.val() + '">' + $this.text() + '</li>');
});

$('#test').html(listitems.join(""));
cballou
Great idea with the rel tag. Thinking about the next step is good work...
KyleFarris