Add multiple people using Javascript Client Object Model

I am trying to add multiple people to a SP column of type Person/Group i.e. people picker. I am able
to add one successfully using their userId, but HAVE no clue how to do that for multiple people. Here is the code for one user:
function UserDrop(e, toElement, listGuid, columnName) {
//EcmaScript Client Object Model
var ctx = new SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getById(listGuid);
var item = list.getItemById(elementId);
//columnName is of type person/group and I am adding user //whose userId is 7
item.set_item(columnName, 7);
item.update();
// asynchronous call
ctx.executeQueryAsync(
function () { toElement.innerHTML = userLinkHtml; },
function () {alert ("Error")}
return false;
This works great and I can add user whose userId is 7, however I want to add multiple people like let's say users of user Ids 7 and 8. 
Any ideas or help will be greatly appreciated. 
There is a thread on this one but that's from .net COM which could accessed here: http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/5183e87c-ee1d-4594-9492-0dfdf6616cce
7929

Hi ,
Can somebody let me know how the same(assigning the array values to lookup value field) can be achieved with multi-select lookup value. SP.FieldLookUpValue do not have any such methods like fromUser. Please help. Please find my code block below
clientContext = new SP.ClientContext.get_current();
if (this.clientContext != undefined && clientContext != null) {
var webSite = clientContext.get_web();
oList = webSite.get_lists().getByTitle("Add New User");
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
var itemid = parseInt($.urlParam('ID'));
var item = oList.getItemById(itemid);
var users = new Array();
users.push(SP.FieldLookupValue.set_lookupId(1));
users.push(SP.FieldLookupValue.set_lookupId(2));
item.set_item('Responsibility', users);
item.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
also i cant use managed client object model.. so pls let me know how to achieve the same using javascript client object model
Ranjani.R

Similar Messages

  • Add attachments to List Item using JavaScript Client object model in SP2010

    Hi All ,
    I have created custom form for submitng data in list using javascript client object model/jquery .
    Now I want to add option to uplaod multiple attachments to that list item also .
    Is there option with client object model for uplaoding attachment.
    Thanks
    M
    Manesh G

    Can you try this and let me know
    using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb _web = _site.OpenWeb())
         //Let's suppose your Item Id is 1
         int ItemId = 1;
         SPList  oList = _web.Lists["EmployeeList"];
         SPListItem  _item = oList.GetItemById(ItemId);
         if (FileUpload1.HasFile)
               _web.AllowUnsafeUpdates = true;
              Stream fs = FileUpload1.PostedFile.InputStream;
              byte[] _bytes = new byte[fs.Length];
              fs.Position= 0;
              fs.Read(_bytes, 0, (int)fs.Length);
              fs.Close();
              fs.Dispose();
              _item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
              _item.Update();
              _web.AllowUnsafeUpdates = false;

  • Read versions of comments field using javascript client object model

    Hi,
     Does someone knows how to Read versions  of comments field in 'tasks' list using javascript client object model?
    Thanks
    Manvir

    Hi,
    According to your description, I know you want to read versions of comments field.
    We can use the
    SPServices to achieve it. The below code for your reference:
    $().SPServices({
    operation: "GetVersionCollection",
    async: false,
    strlistID: "tester",
    strlistItemID: 1,
    strFieldName: "comments",
    completefunc: function (xData, Status) {
    $(xData.responseText).find("Version").each(function(i) {
    console.log("Name: " + $(this).attr("Information") + " Modified: " + $(this).attr("Modified"));
    More information:
    http://spservices.codeplex.com/releases/view/81401
    Best Regards,
    Dennis Guo

  • SharePoint 2013 implement simple logout button which do not redirect to default sign out page using JavaScript client object model

    I am using windows authentication in my web application.
    My requirement is to implement a sign out button which will sign out the user without having him to close the browser and application should not ask him to login again.
    I tried following two options:
     1. Redirecting the user to default signout.aspx page " /_layouts/15/SignOut.aspx "
     2. Using "Sign In as a different user" URL " /_layouts/15/closeConnection.aspx?loginasanotheruser=true "
    In first case, user is redirected to default sign out page but he can press "Go Back to Site" link to revisit the site. Another major issue is that the user has to close the browser to sign out from the application completely, which is not desirable
    in my project requirement.
    In second case, the the current user is signed out of the application but if the user has saved the password in browser, he gets signed in automatically to the application.
    I also came across the solution where we replace the default sign out page with a custom sign out page, but I am not sure whether it can be implemented using JavaScript Client Object Model of SharePoint.

    Hi 
    I'm basically looking for the exact answer for the query.
    Meanwhile you need to go through the link mentioned below in order to understand how to do it.
    Debugging and Logging Capabilities in SharePoint 2010
    Indul Hassan
    Microsoft Community Contributor
    http://www.indulhassan.com
    You Snooze.. You Lose !!

  • CAML Query to get specific item in folder based on dropdown value using Javascript client object model

    Hi,
    I am using the Javascript Client object model.
    I have a custom list and a custom document library.
    Custom list contains 2 columns - dlName , dlValue
    The document library contains 2 folders - "folder1" ,  "folder2" and contains some images.
    The image name starts with the "dlValue" available in the custom list
    I am using a visual webpart and using javascript client object model.
    I am trying to achieve the below functionality:
    1) Load a dropdown with the custom list.
    2) set the image based on the value in dropdown.
    I have achieved the first option, I have set the dropdown, but not sure how to query the folder and set the image.
    Below is the code i have used so far:
    //In Visual webpart
    <select id="ddlTest" >
    </select>
    <br/>
    <div id="PreviewLayer">
    <img id="imgPlaceHolder" runat="server" alt="Image" title="imgPlaceHolder" src=" " />
    </div>
    // In Javascript file
    function RenderHtmlOnSuccess() {
    var ddlTest = this.document.getElementById("ddlTest");
    ddlTest.options.length = 0;
    var enumerator = this.customListItems.getEnumerator();
    while (enumerator.moveNext()) {
    var currentItem = enumerator.get_current();
    var dropdownValue = currentItem.get_item("dlValue");
    ddlTest.options[ddlTest.options.length] = new Option(currentItem.get_item("dlName"), dropdownValue);
    setImage(dropdownValue); // Not sure how to query the folder and set the image based on value.
    // Also if dropdown value is changed, corresponding image should be shown
    How to query the folder and based on dropdown value, show the image? Also, how to handle the dropdown value change?
    Thanks

    Hi,
    Here are two links for your reference:
    Example of how to Get Files from a Folder using Ecmascript \ Javascript client object model in SharePoint 2010
    http://sharepointmantra.wordpress.com/2013/10/19/example-of-how-to-get-files-from-a-folder-using-ecmascript-javascript-client-object-model-in-sharepoint-2010/
    SP2010 JSOM Client Object Model: How to get all documents in libraries including all folders recursively
    http://sharepoint.stackexchange.com/questions/70185/sp2010-jsom-client-object-model-how-to-get-all-documents-in-libraries-including
    In SharePoint 2013, we can also use REST API to achieve it.
    http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • Get current item id using JavaScript Client Object Model

    I have a client query that query SharePoint list Items. Lets say it is a document library. I need to get the list item id of each. 
    I can query the Title of the document using this syntax.
    ctx.CurrentItem['Title']
    But when I try 
    ctx.CurrentItem['ID']
    for list item ID, it does not give a value. How can I solve this?

    Hi Malin,
    If you're using the JavaScript Client Object Model, try using the SPListItem.get_item('key') method as in the example below:
    <script>
    ExecuteOrDelayUntilScriptLoaded(function(){
    var arrIds = [];
    var clientContext = new SP.ClientContext();
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query></Query></View>');
    var items = clientContext.get_web().get_lists().getByTitle("Your List Title Here").getItems(camlQuery);
    clientContext.load(items);
    clientContext.executeQueryAsync(Function.createDelegate(this,function(){
    var itemEnumerator = items.getEnumerator();
    while(itemEnumerator.moveNext()){
    var itemId = itemEnumerator.get_current().get_item('ID');
    arrIds.push(itemId);
    alert(arrIds);
    }), Function.createDelegate(this, function(){
    alert("something went wrong");
    },"SP.js");
    </script>

  • Getfilebyserverrelativeurl not working in Javascript client object model

    Hi,
    I am using the "getfilebyserverrelativeurl" to verify if the file exists. But it does not seem to work.
    I am using Javascript client object model.
    Below is the code used:
    //ImageName = "test1.jpg" . This file does not exist in the below location
    var url = oweb.get_url() + "/Lists/LibraryName/folder1/" + ImageName;
    try {
    var fileUrl = oweb.get_serverRelativeUrl() + "/Lists/LibraryName/folder1/" + ImageName;
    oweb.getFileByServerRelativeUrl(fileUrl);
    window.location = url;
    catch (e) {
    alert("File does not exist.");
    I am not getting any errors in javascript, but the alert is not showing up.
    The file does not exist in the folder, so I am expecting the alert, but in-turn it redirects to "Page not found" OOB page.
    How to fix this?
    Thanks

    Hello,
    I see a few odd things with that code.
    Try it with the following changes and see if it makes a difference:
    // declared globally
    var fileName= "";
    var fileurl = "";
    function downloadImage(){
    fileName = "image1.zip";
    fileurl = SP.ClientContext.get_current().get_url() + "/LibraryName/foldername/" + fileName;
    var clientcontext = new SP.ClientContext.get_current()
    var oweb = clientcontext.get_web();
    var ofile = oweb.getFileByServerRelativeUrl(fileurl);
    clientcontext.load(ofile);
    clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDownloadfilesOnSuccess), Function.createDelegate(this, this.RenderDownloadfilesOnFailure));
    function RenderDownloadfilesOnSuccess() {
    window.location = fileurl;
    function RenderDownloadfilesOnFailure(sender, args) {
    alert(fileName + " does not exist.");
    Which version of Internet Explorer are you using for debugging? The F12 developer tools will allow you to debug JavaScript and "step out" of executing JavaScript code so you can trace the problem back to where it originates in your own code
    instead of debugging the resulting errors that crop up in the built-in stuff (like MicrosoftAjax.js)

  • Fetching file size using CAML query in Javascript client object model

    Hi,
    I am using the Javascript client object model to retrieve contents of a document library.
    I have a document library, which contains a folder "Folder1" . "Folder1" has a zip file. I would like to get the file size of the zip file.
    I have tried the below code, but not sure, how to fetch the file size.
    function FetchImage() {
    var clientcontext = new SP.ClientContext.get_current();
    var oweb = clientcontext.get_web();
    var olibrary = oweb.get_lists().getByTitle(DocLibrary);
    var query = new SP.CamlQuery();
    query.set_folderServerRelativeUrl("Lists/DocLibrary/folder1/");
    folder = olibrary.getItems(query);
    clientcontext.load(folder, 'Include(Title,ContentType, FileLeafRef,FileDirRef,File)');
    clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDataOnSuccess), Function.createDelegate(this, this.RenderDataOnFailure));
    function RenderDataOnSuccess() {
    var ListEnumerator = this.folder.getEnumerator();
    while (ListEnumerator.moveNext()) {
    var currentItem = ListEnumerator.get_current();
    if (_contentType.get_name() != "Folder") {
    var File = currentItem.get_file();
    if (File != null) {
    // Fetch file size
    How to fetch the file size?
    Thanks

    <script>
    function getSize()
            var myFSO = new ActiveXObject("Scripting.FileSystemObject");
            var filepath = document.upload.file.value;
            var thefile = myFSO.getFile(filepath);
            var size = thefile.size;
            alert(size + " bytes");
    </script>
    http://social.msdn.microsoft.com/Forums/en-US/e5d2ff3d-01c7-4cc0-a081-29a4dfbb0fad/getting-the-sharepoint-list-attachment-size-using-javascript?forum=sharepointcustomizationlegacy

  • How can I get an item and it's attachments from the current list using SP's JavaScript Client Object Model on newform.aspx?

    I only recently learned/read about SharePoint's JavaScript Client Object Model. I'm reading online trying to figure this out but not having much luck.
    On newform.aspx (and dispform.aspx) I want to get the
    current list,
    the last item created, and it's attachments. I now the CAML query I need to get the last item created, but first I have to get the current list and I am not sure how to do that.
    I tried this but it returns null:
    SP.ListOperation.Selection.getSelectedList()

    Hi,
    For your issue, you can get the list name from the new form url and retrieve the list last created item :
    https://social.msdn.microsoft.com/Forums/office/en-US/b90a64f8-2255-41b0-9d91-78335dd4a4cf/get-list-name-from-list-url-through-javascript?forum=sharepointdevelopmentprevious
    http://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • Print multiple documents in sharepoint client object model

    Hi  All,
    I  have a content editor webpart which displays documents from document library using sharepoint client object model. 
    test1 test2 test3 test4 are documents from document library.
    I have requirement to print the selected documents in single click of print button.
    once I clicks on print button all the selected documents should get printed.
    Is there any way to achieve this....?
    Regards
    Srinivas
    srinivas

    Hi Srinivas,
    You can do this but it will be combination of ECMA and JS. First you need to get selected file name by ECMA script then call a java script function to print documents.
    Here is script to print all docs: http://stackoverflow.com/questions/7187400/printing-multiple-pdf-files-using-javascript
    Hope it could help
    Hemendra: "Yesterday is just a memory,Tomorrow we may never see"
    Whenever you see a reply and if you think is helpful, click "Vote As Helpful"! And whenever
    you see a reply being an answer to the question of the thread, click "Mark As Answer

  • Enable anonymous access for Javascript Client Object Model

    In SharePoint 2010 it was possible to use the Javascript Client Object Model with anonymous access enabled by removing "GetItems" from the ClientCallableSettings.AnonymousRestrictedTypes.
    In SharePoint 2013 however, it seems that an extra security barrier has been implemented. Trying to use the Javascript Client Object Model results in the following message: "Access denied. You do not have permission to perform this action or access this
    resource."
    After this I went on to do a little research, and it appears that Javascript Client Object Model actually relies on the REST API (please correct me if I'm mistaken), and the REST API also doesn't seem to work as an anonymous user.
    So I'm in the dark here. I can't imagine that SharePoint 2013 (so heavily relying on the client object model) can't be used with anonymous access. I've also found very little documentation on anonymous access in combination with SharePoint 2013.
    So, how do I enable the Javascript Client Object Model to be used with anonymous access enabled?
    P.S. Needless to say, my web application is enabled for anonymous access and so is my site collection.

    There are really 4 things you need to do to enable anonymous access:
    1. In web application level, enable anonymous.
    2. In site collection level, make sure anonymous access Entire Website.
    3. In Web level, set Full Permission Masks, till here, you're able to anonymously access REST APIs.
    # Enable Anonymous access
    $web = Get-SPWeb $url
    if($web -ne $null)
        Write-Host
        Write-Host -ForegroundColor Yellow "Enabling Anonymous access on:" $web.Url
        Write-Host
        $web.AnonymousState = "On"
        Write-Host -ForegroundColor Yellow "AnonymousState set to:" $web.AnonymousState
        $web.AnonymousPermMask64 = "FullMask"
        Write-Host -ForegroundColor Yellow "AnonymousPermMask64 set to:" $web.AnonymousPermMask64
        $web.Update()
        Write-Host
    Below are the things to enable anonymous client object model APIs:
    4. In web application level, Require Use Remote Interfaces Permission - uncheck it.
    5. In web application level, Anonymous Restricted Types, remove all of them:
    $app.ClientCallableSettings.AnonymousRestrictedTypes.RemoveAll()

  • Error in Application.Run(DisplayLoginForm) and Remote Authentication in SharePoint Online Using the Client Object Model

    Hi guys
    I Think that is a simple error, but I don’t have enough knowledge in .NET apps.
    I make an console app that use Remote Authentication in SharePoint Online Using the Client Object Model, that a I downloaded from MSDN.
    This App run ok.
    But when I like to make a Windows From App. This component send me an error in Application.Run(DisplayLoginForm)
    This err msg :
     An unhandled exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll
    Additional information: Starting a second message loop on a single thread is not a valid operation. Use Form.ShowDialog instead.
    Is there any way to use a form inside a windows form?
    Thank in advance
    Ramiro
    Ramiro B

    Hi,
    Based on the error message, please do as following:
    1. Check your code logic below:
    void btn_Click(object sender, System.EventArgs e)
    Thread t = new Thread(StartMyForm);
    t.TrySetApartmentState(ApartmentState.STA);
    t.Start();
    public static void StartMyForm()
    Application.Run(new MyForm(..));
    2.Try to add the following code line in your code.
    Application.Restart();
    If the issue still exists, please provide your requirement and code for a further research.
    Best Regards
    Dennis Guo
    TechNet Community Support

  • How to get all previous versions page contents of a publishing page using SharePoint Client Object Model 2010

    How to get all previous versions page contents and other field values of a publishing page using SharePoint Client Object Model 2010?
    Thanks,
    Osmita

    Hi Osmita,
    Greetings.
    Here are the links that helps you. It has code attached to it.
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/a0d2ab40-99ba-4368-8505-1dc559ef6469/get-content-of-previous-version-of-page-sharepoint-2010?forum=sharepointgeneralprevious
    http://social.technet.microsoft.com/Forums/sharepoint/en-US/faaf419f-997e-4150-9911-48cc375c3b46/how-to-get-previous-published-versions-of-publishing-pages-in-sharepoint-2010?forum=sharepointdevelopmentprevious
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • Cannot download master page using managed client object model SharePoint 2010

    string siteUrl = "http://server:port/sites/demo";
    string fileServerRelativeUrl = @"/sites/demo/_catalogs/masterpage/v4.master";
    using (ClientContext context = new ClientContext(siteUrl)){ FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(context, fileServerRelativeUrl);}
    File.OpenBinaryDirect() throws "The remote server returned an error: (404) Not Found" error. while Microsoft.SharePoint.Client.File f1 = web.GetFileByServerRelativeUrl(fileUrl);
                    context.Load(f1);
                    context.ExecuteQuery();this gives the file object.File.OpenBinaryDirect() works if I pass "/sites/demo/_catalogs/masterpage/TabViewPageLayout.aspx" as fileServerRelativeUrl.Both the files are present in Master Page Gallery.File.OpenBinaryDirect() doesn't work if I pass any of ".master" file in the master page galleryPlease let me know whether downloading the master pages is supported using managed Client object model. 

    Hi,
    If don't change the default config, We are unble to download master page.
    It's better to create your own (perhaps based on the default.master) and use that master page.
    also,make sure there's no a permission issue on the website.
    Thanks
    Guangchao chen
    TechNet Community Support

  • The remote server returned an error: (401) Unauthorized. while running client context using sharepoint client object model

    Hi,
    I have started using the client object model so that i do not have to go to sharepoint admins to perform some basic operations on remote server. While assigning list item level permission i am getting following error, could you please help. thanks.
    The remote server returned an error: (401) Unauthorized.
       at
    System.Net.HttpWebRequest.GetResponse()
       at
    Microsoft.SharePoint.Client.SPWebRequestExecutor.Execute()
       at
    Microsoft.SharePoint.Client.ClientContext.EnsureFormDigest()
       at
    Microsoft.SharePoint.Client.ClientContext.ExecuteQuery()
       at
    SetDowntimeItemPermission.SetPermission.Main(String[] args) in

    it seems your request was unauthenticated i'm not sure are you using a web application with FBA or desktop application my suggestion would be try to impersonate your request by passing network credentials (COM works on network credentials )
    NetworkCredential credentials = new NetworkCredential("username", "pwd", "domain");
    ClientContext context = new ClientContext("http://site-url");
    context.Credentials = credentials;
    Best Regards, Ashutosh | SharePoint World

Maybe you are looking for

  • 3 Phones on current family plan - Can i Switch a phone(#) without penatly?

    Here is the situation: My girlfriend pays for the Family Plan and has 3 phones on it (hers, her mom's, and her EX-boyfriend). I have an individual account which I am currently eligible to update my phone (which i wanted the Droid X), BUT my contract

  • Save PDF Filler Forms

    I have created a PDF using Adobe Designer 7.0. Is there a way to allow a person viewing the PDF to fill information and then save a copy of that form and retain the information he/she entered?

  • Mosaic doesn't work for printing cd covers

    Tried to use Mosaic to make a CD insert that would show all the album covers in a playlist I was burning to CD. All tunes purchased from the iTMS and all came with artwork (it showed as I played the tracks). But when I chose Print from the file menu,

  • Since updating to OS 6 trouble staying connected to wifi how do I fix this problem?

    Since updating to OS 6 trouble staying connected to wifi how do I fix this problem?

  • About RSCRM_BAPI transaction

    Hi i am about to run a query using Transaction RSCRM_BAPI. The Extract will be stored as CSV file in Application server. But the process is running over two hours but still is not completed. Can any one help in this regard...