Maurice
Maurice

Reputation: 1092

jQuery duplicate select options in list

I have the following situation

<div class="selectContainer">
<select size="1" id="kind">
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
</div>

<div id="second"> <ul id="test"></ul></div>

I want jQuery to automatically duplicate the option values in a list, so i will get the following HTML

<div id="second">
<ul id="test">
<li id="one">one</li>
<li id="two">two</li>
<li id="three">three</li>
</ul>
</div>

I thought the following would work, but it doesn't. I gives me one list item with 'undefined' in it

 
$(function(){
 $("#kind").each(function () {
  li = '<li id="'+$(this).attr('value')+'">'+$(this).attr('text')+'</li>';
  $("#test").html(li);
 });
});

Upvotes: 2

Views: 1537

Answers (5)

karim79
karim79

Reputation: 342635

Another way, just for fun (plus it is both concise and efficient enough):

$("#test").html($("#kind > option").map(function() {
    return '<li id="' + this.value + '">' + $(this).text() + '</li>';
}).get().join(""));

Try it here.

In case it is of any interest, here is a decent discussion on normal string appends vs Array.join():

Upvotes: 1

Shef
Shef

Reputation: 45589

Try:

$(function(){
    var lis = '';
    $("#kind option").each(function () {
        lis += '<li id="'+$(this).val()+'">'+$(this).text()+'</li>';
    });
    $("#test").html(lis);
});

You were trying to iterate over #kind, which is a single element, the select element. You should be iterating over options. Furthermore, you were resetting the HTML of all the UL every time you were iterating.

Check it here

Upvotes: 1

Phil
Phil

Reputation: 11175

Here is a working jsfiddle: fiddle demo

$(function(){
    var li = '';
    $("#kind option").each(function () {
        li += '<li id="'+$(this).attr('value')+'">'+$(this).text()+'</li>';

    });
    $("#test").html(li);
});

Upvotes: 0

Bj&#246;rn
Bj&#246;rn

Reputation: 2648

Try using

$("option", "#kind").each(function () {

instead, it looks like the select itself is being converted as well

Upvotes: 0

Jeremy B.
Jeremy B.

Reputation: 9216

You are close, it should be

$(function(){
   $("#kind option").each(function () {
      li = '<li id="'+$(this).val()+'">'+$(this).text()+'</li>';
      $("#test").append(li);
   });
});
  1. you need to get the options, your selector only retrieved the select element.
  2. You need to use .val() and .text(). The attr won't find what you need.
  3. You need to use .append(), using .html() will simply overwrite the content each time you loop through.

Upvotes: -1

Related Questions