ben tedder : code things

SPServices example: populate a drop-down menu

Here's a fairly basic tutorial on how to populate a drop-down menu (select menu) using the jQuery library for SharePoint Web Services (SPServices) .

First, let's setup our body with one simple, empty, html "select" tag:

<select class="list-selector"></select>

Next, up in the head of our document, we need to call 2 scripts. First, jQuery itself, and then the SPServices library:

<script src="/Style Library/scripts/jquery-1.6.4.min.js"></script>
<script src="/Style Library/scripts/jquery.SPServices-0.7.0.min.js"></script>

And now for the good part. We're going to call a function that pulls every list title in our site and creates a new option for each one in our drop-down menu.

<script type="text/javascript">
    $(document).ready(function(){
        //begin getLists function
        function getList(){
            $().SPServices({
                operation:"GetListCollection",
                webURL: $(this).attr("WebFullUrl"),
                async:false,
                completefunc: function(xData, Status) {
                    $(xData.responseXML).find("List").each(function(){
                        listTitle = $(this).attr("Title");
                        listItem = "<option>" + listTitle + "</option>"
                        $("select.list-selector").append(listItem);
                    })
                }
            })
        } // end function
        getList();
    }); // end document ready
</script>

You can see, after the "GetListCollection" operation is complete, we create a new variable called "listTitle" and give it the "Title" attribute of the list. Then we create another variabled called "listItem" that includes the surrounding "option" tags as well as the first "listTitle" variable we created. This entire variable is then appended to the select list.

Voila!