select multiple rows in sharepoint and add the amount in amount column in Js

Nadda Muhammad 60 Reputation points
2023-08-04T05:24:07.7766667+00:00

i have many rows in a list. when i select multiple row i want their amount to be added and displayed using JavaScript

SharePoint
SharePoint
A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.
11,230 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
3,572 questions
{count} votes

Accepted answer
  1. RaytheonXie_MSFT 40,441 Reputation points Microsoft External Staff
    2023-08-17T02:03:05.12+00:00

    Hi @Nadda Muhammad,

    I'm glad to hear you solve the problem ,if you have any issue about SharePoint, you are welcome to raise a ticket in this forum.

    By the way, since the Microsoft Q&A community has a policy that "The question author cannot accept their own answer. They can only accept answers by others." and according to the scenario introduced here: Answering your own questions on Microsoft Q&A, I would make a brief summary of this thread:

    [select multiple rows in sharepoint and add the amount in amount column in Js]

    Issue Symptom:

    How to select multiple items in sharepoint list and get the sum of some field value. Then pass the data to a new form and set the default value by the caculated value.

    Solution:

    Solved by setting the variable in a workflow and using following code

    <script type="text/javascript">
    
      function getUrlParameter( name ){
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null ) return "";
        else return results[1];
        }
      
      function populateNewForm(){
        document.getElementById("Training_67194962-c685-4033-8744-701fd9f26beb_$LookupField").value = getUrlParameter("Training");
      }
      _spBodyOnLoadFunctionNames.push("populateNewForm")
    </script>
    

    Here is the link for reference

    Pass URL parameter to SharePoint new form (NewForm.aspx) to auto-populate a lookup field


    You could click the "Accept Answer" button for this summary to close this thread, and this can make it easier for other community member's to see the useful information when reading this thread. Thanks for your understanding!

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Nadda Muhammad 60 Reputation points
    2023-08-16T10:05:16.7066667+00:00

    @RaytheonXie_MSFT i got the solution form the link. hope it helps someone

    0 comments No comments

  2. RaytheonXie_MSFT 40,441 Reputation points Microsoft External Staff
    2023-08-07T09:12:38.2333333+00:00

    Hi @Nadda Muhammad,

    Per my test, I can use following code to count the items selected and caculate the total amt then create a new item in another list.

    		<script src="https://code.jquery.com/jquery-2.2.4.js" type="text/javascript"></script>	
    		<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    		<script type="text/javascript" src="/_layouts/15/sp.js"></script>
    		<script>
    			function getselected(){
    				var ctx = SP.ClientContext.get_current();
    				
    				var items = SP.ListOperation.Selection.getSelectedItems(ctx);
    				
    				//alert (Object.keys(items).length);
    				console.log(Object.keys(items).length);
    				var count = Object.keys(items).length;
    				var ids = [];
    				
    				items.forEach((item) => {
    					var itemid = item.id;
    					console.log(itemid);
    					
    					ids.push(itemid)
    				});
    				
    				var web = ctx.get_web();
    				var list = web.get_lists().getByTitle('ListTest11');
    				var result = []; //for storing items 
    				ids.forEach(function(id){
    				    var item = list.getItemById(id);
    				    ctx.load(item);
    				    result.push(item);
    				});
    				ctx.executeQueryAsync(
    				  function() {
    				     result.forEach(function(item){
    				         var amt = 0;
    						amt += item.get_item('Amt');
    						console.log(amt);
    						// Specify list title here
    						var oList = web.get_lists().getByTitle("ListTest12");
    										 
    						// Get Item using CAML Query
    						var camlQuery = new SP.CamlQuery();
    										 
    						// New "ListItemCreationInformation" Object
    						var oListItemCreationInformation = new SP.ListItemCreationInformation();
    										 
    						var oListItem = oList.addItem(oListItemCreationInformation);
    										 
    						// Set value for each column here
    						oListItem.set_item('AmtTotal', amt);
    						oListItem.set_item('Count', count);
    										 
    						oListItem.update();
    										 
    						ctx.load(oListItem);
    										 
    						// Execute the query to the server.
    						ctx.executeQueryAsync(onsuccess, onfailed);
    				     });
    				  },
    				  function(sender,args){
    				     console.log(args.get_message());
    				  }
    				); 
    		
    			}
    			
    			function onsuccess() {
    			    console.log("Success");
    			}
    			 
    			function onfailed(sender, args) {
    			    console.log('Failed' + args.get_message() + '\n' + args.get_stackTrace());
    			}
    		</script>
    		<button onclick="getselected()" type="button">add selected</button>
    

    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. RaytheonXie_MSFT 40,441 Reputation points Microsoft External Staff
    2023-08-11T08:10:32.0466667+00:00

    Hi @Nadda Muhammad,

    First we insert the following code into list_1. This code will caculate the sum of rows and redirect to the list_2 newform.

    function calculateSumAndSendData(selectedRows) {
        var sum = 0;
    
        for (var i = 0; i < selectedRows.length; i++) {
            var listItem = selectedRows[i];
            var columnValue = listItem.get_item('Amt'); // Replace 'ColumnName' with the actual column name you want to sum
            sum += columnValue;
        }
         alert(sum);
         window.location.href = "http:**********************/NewForm.aspx";
    }
    

    Then we need to insert following code to set default value for the new form of list_2.

      $(document).ready(function() {       
           $("select[title='AdjustmentAmount']").val(sum);
      }); 
    

    But we are unable to get the parameter sum from list_1. So we can only set a constant but not a variable for default value.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.