Blog

Adding Dropdown using REST API and Jquery

You want to create a dropdown list with values from another list. If the list exists in the same site you can use lookup field column but if the list is in another site or site collection, you cannot do it using Lookup Column

Here is the REST API method that uses jQuery to get data from another list and display as dropdown.

  1. Add script editor web part and add below code
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.1.min.js"></script>

<script>
    $(document).ready(function() {

        countriesDrpDownBind();

    });

    function countriesDrpDownBind() {

        var listName = "countries";

        var url = _spPageContextInfo.webAbsoluteUrl;



        getListItems(listName, url, function(data) {

            var items = data.d.results;



            var inputElement = '<select id="drpcountries"> <option  value="">Select</option>';

            // Add all the new items

            for (var i = 0; i < items.length; i++) {

                var itemId = items[i].Title,

                    itemVal = items[i].Title;

                inputElement += '<option value="' + itemId + '"selected>' + itemId + '</option>';



            }

            inputElement += '</select>';

            $('#divisiondrp').append(inputElement);



            $("#drpcountries").each(function() {

                $('option', this).each(function() {



                    if ($(this).text() == 'Select') {

                        $(this).attr('selected', 'selected')

                    };

                });

            });

            // assign the change event to provide an alert of the selected option value

            $('#drpcountries').on('change', function() {

                alert($(this).val());

            });



        }, function(data) {

            alert("Ooops, an error occured. Please try again");

        });

    }

    // READ operation

    // listName: The name of the list you want to get items from

    // siteurl: The url of the site that the list is in.

    // success: The function to execute if the call is sucesfull

    // failure: The function to execute if the call fails

    function getListItems(listName, siteurl, success, failure) {

        $.ajax({

            url: siteurl + "/_api/web/lists/getbytitle('" + listName + "')/items?$orderby=Title asc",

            method: "GET",

            headers: {
                "Accept": "application/json; odata=verbose"
            },

            success: function(data) {

                success(data);

            },

            error: function(data) {

                failure(data);

            }

        });

    }
</script>

Division

<div id="divisiondrp"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *