Wednesday, July 23, 2014

Retrieving list items using JSOM

The below code adds the list title to a html control

<select id="ddlTitle" multiple="multiple"></select>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
function retrieveListItems() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Announcements');
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
        '<Value Type=\'Number\'>1</Value></Geq></Where></Query><RowLimit>10</RowLimit></View>');
    this.collListItem = oList.getItems(camlQuery);
    clientContext.load(collListItem);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));            
}

function onQuerySucceeded(sender, args) {
    var option='';
    var oListItem='';

    var listItemEnumerator = collListItem.getEnumerator();
    var ddlTitle=document.getElementById("ddlTitle");
    while (listItemEnumerator.moveNext()) {
        oListItem = listItemEnumerator.get_current();
        option=document.createElement("option");
        option.text=oListItem.get_item('Title');
        ddlTitle.add(option);      
    }
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>​​​​​​​​​​​​​​​​​

No comments:

Post a Comment