Get selected listitems with JavaScript

In some cases you need to do something with the selected items in a list. You can access the items by using some simple JavaScript code:

 

function GetSelectedItems(){

   var ctx = SP.ClientContext.get_current();

   var items = SP.ListOperation.Selection.getSelectedItems(ctx);

   var item;

   for(item in items){

      alert("selected item id: " + items[item].id));

   }

}

You can use this code in a HTML Form WebPart or create a Ribbon button and call this function.