I have a list
<ul id="list">
<li>list1</li>
<li>list2</li>
<li>list3</li>
开发者_运维知识库</ul>
and text box
<input type="text" name="textfield" id="tb" value="" />
When i click a button, all the list items should be in the textbox like this
list1 list2 list3
I want to do this in jquery. Please help me.
Read about .each() jQuery method for understanding the following snippet:
<input type="button" id="populate" value="Populate" />
<script type='text/javascript'>
    $('#populate').click(
        function() {
            $('#tb').val('');
            var list_items = new Array;
            $('#list li').each(
                function(i, list_item) {
                    list_items.push(list_item.innerHTML);
                }
            );
            $('#tb').val(list_items.join(' '));
        }
    );
</script>
Using .map() is a great solution for this sort of situation.
It builds an Array (actually a jQuery object) for you automatically.
You then use .get() to grab the Array, and .join() to join the elements into a string.
$('#button').click(function() {
    var result = $('#list li').map(function() {  // .map() will iterate over the <li> elements.
        return $(this).text();  // Each iteration will return the text value in the element
    }).get().join(" ");         // Grab the Array, and join with a blank space
    $('#tb').val(result);   // Set the value of your input
});
Relevant jQuery docs:
- .map()- http://api.jquery.com/map/
- .get()- http://api.jquery.com/get/
Add a button and apply onclick="myfun()":
<button onclick="myfun()">click here to add</button>
Try this:
function myfun(){
        if($("#tb").val()==""){
            alert("enter the value");
        }
        else{
            var a =$("#tb").val();
            $("#list").append("<li>"+a+"</li>");
        }
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论