Reputation: 1092
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
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(""));
In case it is of any interest, here is a decent discussion on normal string appends vs Array.join()
:
Upvotes: 1
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.
Upvotes: 1
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
Reputation: 2648
Try using
$("option", "#kind").each(function () {
instead, it looks like the select itself is being converted as well
Upvotes: 0
Reputation: 9216
You are close, it should be
$(function(){
$("#kind option").each(function () {
li = '<li id="'+$(this).val()+'">'+$(this).text()+'</li>';
$("#test").append(li);
});
});
Upvotes: -1