How to enumerate the selected list items with JavaScript

In SharePoint 2010 you can select multiple list items in a list by checking the checkbox in front of the item. That is an option you can enable (by default) or disable in the view settings. The purpose of that selection is to do some actions on multiple items at once (deleting for example). The actions are enabled in the ribbon. You can use Visual Studio to add your own custom actions to the ribbon but when you are unable to deploy solutions to the server you can also use JavaScript to enumerate the selected items and do something with them. This example enumerates all the selected items in a list “Project” and changes the project status for each item.

To start I created a new page and added the Project list web part to it and a HTML form Web Part. I will use the HTML form Web Part to store my JavaScript code in it.

Add the following code in the source editor of the HTML form Web Part:

<input type="button" id="goedkeurenprojecten" value="Change status" onclick="ProjectenGoedkeuren();" />

<script>

function ProjectenGoedkeuren(){
   var context = SP.ClientContext.get_current();
   var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
   var list = context.get_web().get_lists().getByTitle("Project");
   var item;
   for (item in selectedItems){
         //change status id:9
         var projectItem = list.getItemById(selectedItems[item].id);
         projectItem.set_item("Status",9);
         projectItem.update();
         context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
         }
   window.location=document.location;
}

function onQuerySucceeded() {
//    alert(‘Item updated!’);
}

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

As you can see I use the JavaScript Client Script SDK. With the method getSelectedItems() I get a list of all the checked items. Then I use some basic code to update each list item. The changes are done asynchronous so you must use some delegate functions the alert the user. 

You can do a lot more with the JS SDK. Check it out!