开发者

How to Add the list item to textbox in jquery?

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>");
        }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜