tags:

views:

22

answers:

2

Hello, 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.

+2  A: 

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>
Alan Haggai Alavi
A: 

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:

patrick dw
Hey thank you, very much !
Aakash Chakravarthy
@Aakash - You're welcome! :)
patrick dw