HTML + JQuery (CSOM) to add multiple item to a Sharepoint list and get their IDs

Hi everyone.
I try to use HTML + JQuery in CEWP to build some sort of analog of InfoPath's repeating table in order to be able to insert multiple items in a Sharepoint list using CSOM.
The current task is to get the IDs of inserted items (in order to use those IDs later to add attachments to the list items) as soon as they are added to the list. I've tried several ways but couldn't get the IDs of all inserted items. Usually
I get "-1" as an ID for every item except the last one, which returns me the correct ID. 
Bellow is the code.
<script src="/testsite1/SiteAssets/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="/testsite1/SiteAssets/jquery.SPServices.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var click = 1;
$("#btn_id_1").click(function() {
click ++;
$("#tr_id_1").clone().appendTo("#tbl_id_1").attr("id", "tr_id_" + click.toString()).find("input").val("");
$("#btn_id_2").click(function() {
Save();
function Save() {
var ctx = new SP.ClientContext.get_current();
var taskList = ctx.get_web().get_lists().getByTitle('Tasks');
var taskItemInfo = new SP.ListItemCreationInformation();
var vendor;
var certname;
var certid;
$("#tbl_id_1 tr").each(function() {
vendor = ($(this).find(".vendor")).val();
certname = ($(this).find(".certname")).val();
certid = ($(this).find(".certid")).val();
newTask = taskList.addItem(taskItemInfo);
newTask.set_item('Title', vendor);
newTask.set_item('Request_', certname);
newTask.set_item('h', certid);
newTask.update();
ctx.load(newTask);
ctx.executeQueryAsync(addTaskSuccess, addTaskFailure);
//timeout();
function timeout() {
alert ("!!!");
function addTaskSuccess(sender, args) {
alert(newTask.get_id());
//AddAttachment(newTask.get_id())
function addTaskFailure(sender, args) {
//alert(newTask.get_id());
alert("no");
window.location = window.location.pathname;
</script>
<div id="div_id_1" class="div_class_1">
<table id="tbl_id_1">
<tbody>
<tr id="tr_id_1">
<td>Vendor:<br><input type="text" class="vendor" /></td>
<td>Cert. Name:<br><input type="text" class="certname" /></td>
<td>Cert. ID:<br><input type="text" class="certid" /></td>
<td>Attachment:<br><input type="file" class="attachment" /></td>
</tr>
</tbody>
</table>
<div><button id="btn_id_1" type="button" width="10" height="10">+</button></div>
<div><button id="btn_id_2" type="button">Save</button></div>
</div>

Here's a working solution (thanks to
this guy)
<script src="/testsite1/SiteAssets/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="/testsite1/SiteAssets/jquery.SPServices.min.js" type="text/javascript"></script>
<script type="text/javascript">
var array = [];
$(document).ready(function() {
var click = 1;
$("#btn_id_1").click(function() {
click ++;
$("#tr_id_1").clone().appendTo("#tbl_id_1").attr("id", "tr_id_" + click.toString()).find("input").val("");
$("#btn_id_2").click(function() {
//Save();
//Call();
var asyncPromises = Save();
asyncPromises.done(function(result) {
//alert(array.length);
console.log(array.length);
for (var i=0; i<array.length; i++) {
//alert(array[i].get_id());
console.log(array[i].get_id());
asyncPromises.fail(function(result) {
function Save() {
var buildDeferredSaves = $.Deferred(function() {
//var array = [];
var ctx = new SP.ClientContext.get_current();
var taskList = ctx.get_web().get_lists().getByTitle('Tasks');
var taskItemInfo;
var vendor;
var certname;
var certid;
$("#tbl_id_1 tr").each(function() {
vendor = ($(this).find(".vendor")).val();
certname = ($(this).find(".certname")).val();
certid = ($(this).find(".certid")).val();
taskItemInfo = new SP.ListItemCreationInformation();
newTask = taskList.addItem(taskItemInfo);
newTask.set_item('Title', vendor);
newTask.set_item('Request_', certname);
newTask.set_item('h', certid);
newTask.update();
ctx.load(newTask);
array.push(newTask);
ctx.executeQueryAsync(
function() {
// Successful
buildDeferredSaves.resolve();
function(sender, args) {
// Failure
buildDeferredSaves.reject(args.get_message());
return buildDeferredSaves.promise();
</script>
<div id="div_id_1" class="div_class_1">
<table id="tbl_id_1">
<tbody>
<tr id="tr_id_1">
<td>Vendor:<br><input type="text" class="vendor" /></td>
<td>Cert. Name:<br><input type="text" class="certname" /></td>
<td>Cert. ID:<br><input type="text" class="certid" /></td>
<td>Attachment:<br><input type="file" class="attachment" /></td>
</tr>
</tbody>
</table>
<div><button id="btn_id_1" type="button" width="10" height="10">+</button></div>
<div><button id="btn_id_2" type="button">Save</button></div>
</div>

Similar Messages

  • Tree slow and bug with Add Multiple Items to End

    Hello,
    I use "Add Multiple Items to End" to fill a tree quickly in Labview 8.5.
    In my test example, It's possible to choise an array of 100, 255 or 1000. parents.
    Each parent has 10 children
    100 is correctly, 255 is slowly an 1000 is big bug !
    Y does a solution, or it has Labview major weaknesses with the function tree.
    Thanks for you help.
    A. Carbonnel
    AC
    Attachments:
    Load Tree.vi ‏37 KB

    Here is the response of France rupport labview
    Sir,
    The behavior you observed beyond 1000 elements vi Tree is a known bug of R & D LabVIEW. Pending that it is corrected in a future version, I invite you to use the ActiveX Treeview. He should be able to meet your expectations in terms of number of elements.
    You can see an example of the use of the ActiveX in attachments.
    Sincerely,
    AC
    Attachments:
    Tree view.zip ‏48 KB

  • How can add multiple item in form .

    hi,
    i have a critical problem .i am creating a check in form for hotel .Now problem is when i fill personal details of Customer with his three family member .here i want to enter all three member name and there relationship with customer .so how can i insert three text fild for name and relation ship in middle of form .Member may be three or Five .
    how can i add multiple item in middle of form according to required .
    Thanks
    Manoj

    I'm assuming that you're talking about an Application Express Form here. In that case, have you thought about using a "master-detail" form? Take a look at the example here Adding a Master Detail Form.
    C.

  • How to change the url of "Add New Item" of a particular list in SharePoint 2013???

    Hi Guys,
    How to change the url of "Add New Item" of a particular list in SharePoint 2013???
    I need to redirect it into the page where I have created my Visual web part.
    Please suggest
    Warm Regards,
    Tony Joy

    Hi,
         There are multiple ways to change the form url like javascript, SharePoint designer, custom code, editing default form to have custom web part etc, Please follow the url below that describe diffent methods and steps
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/ec2769a0-683c-4023-8804-b596e4f92a3a/change-default-forms-on-custom-list?forum=sharepointcustomizationlegacy
    Hope it helps!!!
    Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. Thanks, Ajeet

  • Cannot add new items to a value list in AW database

    I have a database which I have been using for many years. One of the fields is a value list. I just went to add another item to the list, and no matter what I do, the Create button is grayed out. I have another value list in the same database that works fine.
    There are currently 170 items in the value list that is causin the problem, but I didn't think that there was a limit to the number of items that can be is a value list. (At least there is nothing in the AW technical specifications to indicate thin. I duplicated the existing database, deleted about 20 items from the list, then saved the file, and reopened it, and still cannot add new items to that value list. Does anyone know what might be causing the problem?

    Oops
    I read too fast.
    Here is a short script which may help.
    Replace the pop-up item by a text one and edit the property myList in my script to fit your needs.
    Select the field to fill and run the script.
    Then choose an item in the displaid list. It will be pasted in the selected field.
    This trick would give you to work with a "no limit" list of items.
    -- [SCRIPT DB fillFieldFromAlist ]
    Assuming that
    the front document is a database one
    and that a text field is selected,
    run the script to select an item in a list
    and paste it in the field.
    Yvan KOENIG, Vallauris (FRANCE)
    le 19 mars 2007
    property MyList : {"item 1", ¬
    "item 2", ¬
    "item 3", ¬
    "item 4", ¬
    "item 5", ¬
    "item 6", ¬
    "item 7", ¬
    "item 8", ¬
    (* edit the list to fit your needs *)
    tell application "AppleWorks 6"
    activate
    tell document 1
    set laClasse to (get class of selection)
    if laClasse is not field then return (* the selection is not a field *)
    set myItem to choose from list MyList
    if myItem is false then return
    set the clipboard to myItem's item 1
    select menu item 7 of menu 3 (*
    Tout sélectionner •• Select All *)
    paste
    end tell -- document 1
    end tell -- AppleWorks
    -- [/SCRIPT]
    Yvan KOENIG (from FRANCE lundi 19 mars 2007 16:44:53)

  • How to submit a multiple-selection list box in an Infopath Sharepoint form as multiple entries on a Sharepoint list?

    I would like to be able to submit an Infopath form with a multiple selection list box in Sharepoint as multiple entries on a Sharepoint list.
    For example, a user has to complete the following fields:
    First Name:
    Last Name:
    Favorite Color (can select more than one):
    [] Blue
    [] Red
    [] Yellow
    [] Green
    If the user picks blue AND red and submits the form, the Sharepoint list would feature TWO entries, both with their first and last names, but with different colors in the "Favorite Color" column.
    Please let me know if there is a way to do this. Any guidance would be helpful!

    Hi redhotc,
    According to your description, my understanding is that you want to set multiple default values for a multiple checkbox list in InfoPath form.
    I did a test with SQL database table. I set three default values for the checkbox list by adding three values field under the group field(Data->Default values), each value field is for a default value. Then publish it to my SharePoint site, everything
    was fine.Please have a try as the below link:
    http://www.bizsupportonline.net/infopath2010/pre-select-items-multiple-selection-list-box-infopath-2010.htm
    Note: if you are using SQL databse table, you may need to enable ‘Allow cross-domain data access for user form templates that use connection settings in a data connection file’ in CA. More information, please refer to:
    http://answers.flyppdevportal.com/categories/sharepoint2010/sharepoint2010customization.aspx?ID=418b9423-a96c-4e5e-91f9-6a1b010ebb69
    I hope this helps.
    Thanks,
    Wendy
    Wendy Li
    TechNet Community Support

  • Use single realm for multiple web applciation in sharepoint 2013 and adfs 2.0

    Use single realm for multiple web applciation in sharepoint 2013 and adfs 2.0
    Please help!!

    I dont think you can do this, because you have to name/url of the web application in realm. You have to add new realm for each web application.here is script to add another realm.
    Add-PSSnapin "Microsoft.SharePoint.PowerShell"
    $sts = Get-SPTrustedIdentityTokenIssuer | where {$_.Name -eq "ADFS2.0"}
    $uri = new-object System.Uri("http://url/")
    $sts.ProviderRealms.Add($uri, "urn:sharepoint:Name")
    $sts.Update();
    Please remember to mark your question as answered &Vote helpful,if this solves/helps your problem. ****************************************************************************************** Thanks -WS MCITP(SharePoint 2010, 2013) Blog: http://wscheema.com/blog

  • How to update an existing item in a sharepoint list using the WSS adapter for Biztalk

    Is there a way that a record in SP list be updated using WSS adapter in biztalk ?
    BizTalk 2013 and SP 2013 ..
    Regards
    Ritu Raj
    When you see answers and helpful posts,
    please click Vote As Helpful, Propose As Answer, and/or Mark As Answer

    A ListItem has its own unique row id so in all likelihood, an insert with the same data will result in a new list entry. The Lists Web Service however, has an UpdateListItem method which will take an update request. [refer
    http://msdn.microsoft.com/en-us/library/office/websvclists.lists.updatelistitems(v=office.15).aspx ]
    There is another note in the conference (marked answered) to your List Item Update problem. Probably worth a try too. [refer
    http://social.msdn.microsoft.com/Forums/en-US/bee8f6c6-3259-4764-bafa-6689f5fd6ec9/how-to-update-an-existing-item-in-a-sharepoint-list-using-the-wss-adapter-for-biztalk?forum=biztalkgeneral ]
    Regards.

  • Check duplicate items in two sharepoint lists

    Hi, I have 2 separate sharepoint lists, both contrain user names. e.g: Jan Jaap.
    I want sharepoint to automaticly compare those lists to see if there is any name in both lists and notify me about it. For example :
    List 1: Firstname | Surname
              Jan           -    Jaap
              Steen        -    Vos
              george       -    bush
    List 2: Firstname | Surname
              Jan           -    Jaap
              fox            -    washington
              brian         -    potter
    both lists contain jan jaap. and i want sharepoint to notice that and send me and email about it :p.
    Is this in any way possible?
    Thanks in advance!!

    You can use below tool
    http://www.metalogix.com/help/Content%20Matrix%20Console/SharePoint%20Edition/002_HowTo/004_SharePointActions/003_CompareSitesAndLists.htm
    Or if you want to do it programmatic try below:
    http://sharepoint.stackexchange.com/questions/60917/compare-items-of-two-sharepoint-lists
    SPWeb web = SPContext.Current.Web;
    SPList list = web.Lists["Employee"];
    string query = @"<Where>
    <Eq>
    <FieldRef Name='Position' /><Value Type='Choice'>{0}</Value>
    </Eq>
    </Where>
    <OrderBy>
    <FieldRef Name='Salary' Ascending='False' />
    </OrderBy>";
    query = string.Format(query, "Developer");
    SPQuery spQuery = new SPQuery();
    spQuery.Query = query;
    SPListItemCollection items = list.GetItems(spQuery);
    If this helped you resolve your issue, please mark it Answered

  • Get particular item count in sharepoint list using designer Workflow

    How to get specific item count in sharepoint list using designer Workflow 2013.
    For Example 
    Title  Count
    x        1
    y        1
    x        2
    x        3

    HI Thiru,
    Can you please elaborate your problem. Is that Title and count are your list columns you want to fetch the value of count column based on title?
    If my interpretation in not wrong, then it's not possible in SPD with the case you have mentioned in your question as Title='x' is having 3 different entries and SPD activity will always return first matching item and ignore the rest with warning message.
    Regards,
    Brij K

  • Add Multiple Item in database on single click

    hi Friends,
    i have a problem :-
    i have a bill with multiple item eg . Apple (12), Banana (49), Badam (145) , Grapes(25) with there quantity and now i want to Add these item with quantity in my database
    when i finaly click on submit button .
    Actully I have been used tabular form but i am facing one problem when using tabular form ,in Tabular form i enter first item eg . Apple and there quantity eg. *12* in textfield and after click on Add Row Buttom entry went to the database . but i want Entry Shouldn't go in to the database. But only New Row Should Add there when i click on Add Row Button.
    I want all these 4 item should enter in to data base when i click on Final Submit.
    Manoj

    You have to study document [http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14303/advanc.htm#sthref2152] . Every case is other, you have to work hard : ). But it's good addition.
    Now I have no time, I will for 10 hours in forum, if you can't resolve your problem I will help you
    If I help you please grade HELPFUL or CORRECT: )
    Edited by: AndyPol on 2009-09-05 12:47

  • How do I add multiple items to a hitTestObject?

    I have a horizontally scrolling flying game involving a character and diferent types of food moving across the screen from right to left which the character has to collect ("hit"). I have the hitTestObject working for 2 different food movieclips with one item belonging to a healthyList, and the other to a junkList.
    The problem is I don't know how to add more items (movieclips) to each of the lists, so that I have for example 6 items in the healthyList and 4 items in the junkList.
    Below is the code in my Engine.as file. The red highlighted text is the code that creates the problem. I thought that I just needed to add this line in order to add another item to the "healthyList" of food types, but I obviously have it in the wrong place or have the wrong code completely.
    package
        import flash.display.MovieClip;
        import flash.display.Stage;
        import flash.events.Event;
        public class Engine extends MovieClip
            private var numClouds:int = 5;
            private var healthyList:Array = new Array();
            private var junkList:Array = new Array();
            private var myFlying:Flying;
            public function Engine()
                myFlying = new Flying(stage);
                stage.addChild(myFlying);
                myFlying.x = stage.stageWidth / 8;
                myFlying.y = stage.stageHeight / 2;
                for (var i:int = 0; i < numClouds; i++)
                    stage.addChildAt(new Cloud(stage), stage.getChildIndex(myFlying));
                addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
            private function loop(e:Event) : void
                if (Math.floor(Math.random() * 90) == 5)
                    var healthy:Carrot = new Carrot(stage, myFlying);
                    var healthy:Broccoli = new Broccoli(stage, myFlying);
                    healthy.addEventListener(Event.REMOVED_FROM_STAGE, removeHealthy, false, 0, true);
                    healthyList.push(healthy);
                    stage.addChild(healthy);
                    var junk:Hotdog = new Hotdog(stage, myFlying);
                    junk.addEventListener(Event.REMOVED_FROM_STAGE, removeJunk, false, 0, true);
                    junkList.push(junk);
                    stage.addChild(junk);
            private function removeHealthy(e:Event)
                healthyList.splice(healthyList.indexOf(e.currentTarget), 1);
            private function removeJunk(e:Event)
                junkList.splice(junkList.indexOf(e.currentTarget), 1);
    All help and advice very much appreciated.
    Thank you!

    It's good that you don't expect me to do the work for you - saves me from letting you know that.  Doing the work is how you learn.  I am also not here to teach you, and it looks like you might need to get some basics under your belt before you can pursue something like what you are doing now.
    As I already said, the Math.random() method will be one of the key techniques you will need to use for anything you want to have happen randomly.
    Usually it comes in handy with randomly choosing an array's index, where the array stores the different items you want to randomly choose.  In your case, the array could store the names of the different functions you could call for each food item you want to add. Or you could have the classes of the objects in the array and randomly choose which one to load in...
       var foodClasses:Array = new Array("Carrots", "Broccoli", "Hotdog", etc...);
    this approach requires knowing how to dynamically create a new class instance using only a String value.... for example:
        var ClassRef:Class = Class(getDefinitionByName("className"));
        var classInstance:* = new ClassRef();
        addChild(classInstance);
    In that bit of code, the className would be whatever class name you randomly pulled from the array of the class names...
    I didn't say it isn't effective, though it can easily fail being effective as well when your file starts getting bogged down with everything else that is going on.  I said it isn't efficient.  It is constantly fliipping a 120-sided coin, as fast as the file's frame rate to see if it comes up 50 or not.  You could use a setTimeout function or a Timer and get much more efficent performance instead... only processing the code when the time passes. 
    If you cannot understand how that one line of code works, you are probably in over your head and you need to back up to more basic learning before you can tackle something like what you seem to want to create here. 

  • How to autogenrate multiple items report of the SharePoint list and sent to the client id on daily basis

    Dear Support,
    As per customer requirement he want to send SharePoint list multiple items reports on daily basis by email autognrated workflow in SharePoint.
    I tried for that and created workflow for SharePoint list  on new item creation using SharePoint designer 2013 it’s working fine. But I am unable to send list multiple items report by work flow.
    Please let me know the process for SharePoint list multiple items report generation and how to sent mail to the client id on daily basis.
    Would request your support.

    Hi
    another approach
    use a powershell scheduled script which will get needed lists items, adn will sned the infos by email
    Romeo Donca, Orange Romania (MCSE, MCITP, CCNA) Please Mark As Answer if my post solves your problem or Vote As Helpful if the post has been helpful for you.

  • Cannot "Add new Item" in my SharePoint 2010 custom lists

    Hi guys,
                All these days it was working fine and all of sudden now when i click on "Add new item" in the the custom lists which i have created in my SharePoint 2010 and fill in the fields and click "save",
    I am getting an exception...:( 
    Please HELP!!!
    Neo Alpha

    One more thread for the same issue
    http://social.msdn.microsoft.com/Forums/en-US/51f37f3b-18a3-4d6b-b90f-2a4240306bf8/when-update-a-folders-property-it-throw-a-comexception-0x81020089
    hope this will help you
    Senthilrajan Kaliyaperumal

  • PerformancePoint Designer is not loading when clicking on "Add new item" from PerformancePoint Content List

    Hello,
    I am using Internet Explorer 9 to create a new item by launching Performance Point Dashboard Designer from browser. 
    When i click on "Add new item", an Iframe will open showing dashboard design redirect which keep loading for couple of minutes and the designer never opens. 
    Yes, there are working workarounds like opening these links in other tab or opening dashboard designer directly or by clicking on "Run Dashboard Designer"  from BI Center homepage. 
    However, Can someone please help me how to get designer opened when "Add new item" has been clicked from  PerformancePoint Content List from browser? 
    Thanks in advance.
    NKV Prasad Panthangi

    An Update :
    I found this is due to the browser limitation. 
    I have downgraded my Internet Explorer Browser to IE 8 and did the following changes in my browser settings. 
    Tools --> Internet Options --> Navigate to Security Tab --> Click on Custom Level Button --> Under Download --> Select "Enable" radio box for Automatic Prompting for File Downloads. 
    Sadly, I cannot ask users to downgrade their browser to IE 8 because MS already stopped support for this browser and there are no other solution for this except going by workarounds. 
    This clearly says why people are moving away from PerformancePoint Services in SharePoint. 
    Thanks
    NKV Prasad Panthangi

Maybe you are looking for

  • How to track log information in a bean?

    I would like to track some information, e.g., variable value, error, in a bean. I am using System.out.prinln in the bean. I did not see any in the log file of Tomcat5. But this information was shown if from Servelet class. I also tried to pass error

  • I can´t delete files in trash. It stops after a short time undone. What can I do?

    I can´t delete files in trash . It stops after a short time undone. What can I do? There are 52 files in trash, but if I click the button "sure empty" it shows 11.313 files to delete . I would be very greatful for your help!

  • How do you get Adobe Acrobat X Pro to open multiple pdf's in one window

    How do you get Adobe Acrobat X Pro to open multiple pdf's in one window I just got upgraded to Windows 7 64-bit and had to update to Acrobat X Pro. I was using Acrobat 8 Pro on my XP machine and this was nice since i usally have muliple files open at

  • Deleting a fake Apple ID

    Guys It seems someone created an account (the one I have used to log into forums) using my domain name. I didnt create it and Ive received a notification that someone used it to signinto their iphone 5. How can I report this account as a fake account

  • Thread Pool Size

    What can be the maximum thread pool size used in java. What happens if i put up a thread pool size in range of 10k or 20k. how does affect system performance ??? Its quite urgent for me to know. Can someone help out ??? Regards Hrushi