开发者

how to append option text to a list in jquery

开发者 https://www.devze.com 2023-01-19 00:21 出处:网络
I have a tried a few things to get this to work with no luck. I have a select box with a button next to it.When the button is clicked, the text from the currently selected item needs to be placed insi

I have a tried a few things to get this to work with no luck. I have a select box with a button next to it. When the button is clicked, the text from the currently selected item needs to be placed inside li tags and appended to a ul inside another div.

<!--sel开发者_高级运维ect box-->
<div class="select-div">
<select id="select-pub">
<option value="1">Publisher 1</option>
<option value="2">Publisher 2</option>
<option value="3">Publisher 3</option>
<option value="4">Publisher 4</option>
</select>
</div> 

<!--this button needs to append the currently selected text to a list-->

<div class="link-div">
<a class="add-button" href="#" style="width:46px;height:22px;display:block;"></a>
</div>

<!--the option text must now populate this unordered list-->

<div id="publisher-results">
<ul>
</ul>
</div>

I started here, but how can I get the text within li tags and append that to the ul?

<script type='text/javascript'>
$('.add-button').click(function() {

   $('#publisher-results ul').append($('#select-pub :selected').text());
   });
</script>

Any ideas? I've been failing at this all afternoon!


You can create a <li> set the text and append it like this:

$('.add-button').click(function() {
  $('<li />', { text: $('#select-pub :selected').text() })
     .appendTo('#publisher-results ul');
});

You can test it out here, this uses the $(html, props) construction method then uses .appendTo() to place it inside the <ul>, it's broken onto 2 lines just to prevent scrolling on SO, it need not be broken up in your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消