Sum child list items and update parent total using javascript
I have a SharePoint 2010 Parent/Child list setup using a lookup field to join both the lists, this is working well.
The Parent list contains requisition requests and the child list contains related item details. Each of the related child list items has a 'Line Item Total' field. I need to aggregate the Line Item Totals in the child list and place the result in a 'Requisition
Total' in the parent. So for any given parent record the sum of it's related child 'Line Item Totals' is reflected in the 'Requisition' total in the parent row.
I am struggling with the JavaScript code below. I am trying to aggregate Line Item Totals for a given Requisition#? Could someone please review and advise?
<script language="javascript" src="/Purchasing/Documents/jquery-1.8.2.js" type="text/javascript"></script>
<script language="javascript" src="/Purchasing/Documents/jquery.SPServices-2014.01.min.js" type="text/javascript"></script>
<script>
$(document).ready(function()
$('select[title=Requisition#]').children().attr('disabled',true);
$("input[title='Old Amount']").attr("readonly","true").css('background-color','#F6F6F6');
// Retrieve the name of the selected parent item.
var strParent=$("select[title$='Requisition#'] :selected").text();
splist li = web.lists["ReqDetails"]; // This is the child list
spquery q = new spquery();
q.Query= "<Where>" +
"<And>" +
"<Neq>" +
"<FieldRef Name='ID'/><Value Type='Number'>0</Value>" +
"</Neq>" +
"<eq>" +
"<FieldRef Name='LinkID'/><Value Type='Number'>ReqID</Value>" +
"</eq>" +
"<And>" +
"</Where>" +
"<OrderBy>" +
"<FieldRef Name='LineItemTotal'/>" +
"</OrderBy>"
q.ViewFields = string.Concat("<FieldRef Name='LineItemTotal' />");
q.ViewFieldsOnly = true; // Fetch only the data that we need
splistitemcollection items = li.getitems(q);
foreach(SPListItem item in items)
sum += parseInt(item["LineItemTotal"], 10);
alert(sum)
</script>
Rick Rofe
I do something similar for a PO Header/PO Detail set of lists. I use SPServices to pull the data.
I put this code in the child edit page - so any time any child is edited, the parent is updated. I get all children records and total them up (except for the item I'm displaying at the current time. I add that value in directly from the form itself.
<script type="text/javascript" src="/Javascript/JQuery/JQueryMin-1.11.1.js"></script>
<script src="/Javascript/JQuery/jquery.SPServices-2014.01.min.js"></script>
<script>var poNumber = '';
var poDetailID = '';
$(document).ready(function() { var queryStringVals = $().SPServices.SPGetQueryString();
poNumber = queryStringVals["PO"];
poDetailID = queryStringVals["ID"];
function PreSaveAction() {
// update the PO header with the total of all items + shipping + adjustments
var query = "<Query><Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + poNumber + "</Value></Eq><Neq><FieldRef Name='ID' /><Value Type='Counter'>" + poDetailID + "</Value></Neq></And></Where></Query>";
var viewFields = '<ViewFields><FieldRef Name="Total" />';
viewFields += '</ViewFields>';
var poTotal = 0.00;
$().SPServices({
operation: "GetListItems",
async: false,
listName: "PO Details",
webURL: "/po",
CAMLViewFields: viewFields,
CAMLQuery: query,
completefunc: function (xData, Status) {
//alert(xData.responseText);
$(xData.responseXML).SPFilterNode('z:row').each(function() {
if($(this).attr("ows_Total")) {
//alert($(this).attr("ows_Total"));
poTotal += Number(parseFloat($(this).attr("ows_Total").split(";#")[1],2).toFixed(2));
// add in this changed line (we skipped it above)
var qty = $('input[title="Quantity Ordered"]').val();
var price = $('input[title="Price"]').val().replace(',','');
var extend = Number(qty)*Number(price);
poTotal += extend;
//alert(poTotal);
// update the PO Header
$().SPServices({
operation: "UpdateListItems",
async: false,
listName: "Purchase Orders",
webURL: "/po",
ID: poID,
valuepairs: [["Total", poTotal]],
completefunc: function (xData, Status) {
//alert(xData.responseText);
$(xData.responseXML).SPFilterNode('z:row').each(function() {
return true;
Robin
Similar Messages
-
Copy Attachments of sharepoint list item to a document library using Javascript on click of a button
The requirement is as follows:
1. We have a SP list. All items in the list have mulitple attachments.
2. On click of a button, All the attachments of all items should be copied to a document library
This is to be done from client side only. No server code is acceptable. We have tried following things:
1. USing Asynch call
context = new SP.ClientContext("my site name");
this.oWebsite = context.get_web();
var lists = oWebsite.get_lists();
var list = lists.getByTitle('my list name');
context.load(oWebsite);
var folderPath = 'Lists/<my list name>/Attachments/' + folderId;
var Folder = oWebsite.getFolderByServerRelativeUrl(folderPath);
context.load(Folder);
Files = Folder.get_files();
context.load(Files);
context.executeQueryAsync(Function.createDelegate(this, this.ExecuteCopyOnSuccess), Function.createDelegate(this, this.ExecuteCopyOnFailure));
function ExecuteCopyOnSuccess(sender, args) {
for(var p=0;p<this.Files.get_count();p++)
var file = Files.itemAt(p);
var filename = file.get_name();
if (filename != null) {
var newUrl = 'document library url';
file.copyTo(newUrl, true);
context.executeQueryAsync(null,null);
In this case, Files.get_count() throws error - The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
2. Using copy.asmx service
It copies files to document library but some files are blank and are having size 0.
Thanks!Hi,
I think you can use Document Content types or document sets -
Here are links that you can refer to
http://office.microsoft.com/en-us/windows-sharepoint-services-help/introduction-to-content-types-HA010121570.aspx
http://msdn.microsoft.com/en-us/library/office/ms472236(v=office.14).aspx
http://office.microsoft.com/en-us/sharepoint-server-help/create-and-configure-a-new-document-set-content-type-HA101782461.aspx
http://office.microsoft.com/en-us/sharepoint-server-help/introduction-to-document-sets-HA101782466.aspx?CTT=5&origin=HA101782461
Hope this helps!
MCITP: SharePoint 2010 Administrator
MCTS - MOSS 2007 Configuring, .NET 2.0
| SharePoint Architect | Evangelist |
http://www.sharepointdeveloper.in/
http://ramakrishnaraja.blogspot.com/ -
Spotlight lists items and shows preview images. BUT what about showing the path/location address of an item in my computer.
Especially important if I've put the item in the wrong folder and what to locate it without multi-steps. iMac OS X 10.5 was more useful.
Old OSX Spotlight function automatically displayed path/location within the machine: e.g. desktop/folder/sub-folder/item.
Can I make Spotlight show the path?Press option-command and the path is displayed at the bottom of the little preview window. Press command-return and the enclosing folder opens.
-
Using a newly created Library document to create a list item and attach itself
I have a workflow that moves a document from one library to another.
When a document is moved to a certain library I want to create a list item with a link to the document in the list item. Keep in mind there could be 10 files submitted to the library, so then in my list I would want 10 new list items created for
each file, with a link to the individual file. or is there a way to attach the document to a newly created list item programmatically?
is this possible?Hi,
According to your post, my understanding is that you wanted to use a newly created Library document to create a list item and attach itself.
I recommend to create a workflow assocaited to the second library, and start the workflow automatically when an item is created.
Then add action as below:
Best Regards,
Linda Li
Linda Li
TechNet Community Support -
Hello,
Is it possible to submit a list item and at same time query/search the results if parameters are matched.
Example - user logon to site enter search parameters and hit submit button. Once done parameters gets saved in list and shows search results on page. I have been asked to do this with
SP designer and InfoPath doesn’t work due items limits.
Please suggest.
Thanks,
Manish
ManishHi Manish,
may i ask if you need,
when user account click the login button, it will be authenticate the user and then it will show search result page?
may i know how the keyword of words to be put? is it together with the user account box, password and keyword?
or it will be like, after user authenticate, it will redirect to search page, so that user may use the search page to input the keyword?
Regards,
Aries
Microsoft Online Community Support
Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. -
10g: Enabled list items and scrollbars look disabled
Hi,
Is there any way to change the way list items and scrollbars look in 10g?
Enabled list items and scrollbars look disabled to me (the list button on the list item and the arrow buttons on the scrollbars are greyed out).
Visual attributes doesn't seem able to control this.Nope you're pretty much stuck with the look and feel of the decoratiosn unless you want to create your own pluggable component - this would give you more control but you'd have to consider if it's worth the investment.
-
How to print out document list items (and with all comments!)
Hi all,
I am wondering how to get a good printout of document lists.
In a web application I have some document list items and the users are adding many comments in it, so that the document list item doenst show all in the initial view, but scroll buttons to navigate up and down.
I was surprised to read that the standard print functionality doesnt support document items.
http://help.sap.com/saphelp_nw70ehp1/helpdata/en/43/68ce8391886e47e10000000a422035/content.htm
How can I print out a list of all document list items with all comments?
Ist there a workaround?
thanks in advance for sharing your experiences, br, MichaelThanks guys for trying to help me...
Gabriel, I not wanna do "a lot of trix" to get this out of iCal when it should be solved by iCal (from my point of view).
Dancing Brook, Yes I hope we will see that in the future. I am convinced that there is many of us out there who want to see that function in iCal, even if they not really missed it yet.
I have already sent a request to iCal feedback (hope they noted). Maybe they will if we are many doing so... -
Help with select list item and dynamics action
G'Day Apex Gurus,
I having problems trying to achieve to trigger the help window of a select item automatically. A help window is triggered when the select item label is clicked but my client would like to be triguered automatically as soon as the user click to see the options in the select list.
I think that I should be able to do it with dynamic actions but I can not get it to work.
I know when someone click on the label of the select list item trigger this JavaScript
javascript:popupFieldHelp('277938589795252851','1545903379570909')
So I want to trigger the javascript also when the user click of the select list item and pull down the options and for that I think that Dynamic actions is the way to go but I can't get it right.
This is what I a doing:
I created a Dynamic option as follow:
Name : test
Sequence: 30
Even: Click
Selection type: Item(s)
Item(s): P1_RATING <- a selection list item
Condtion: - No Condition -
True Actions
Sequence: 10
Action : Execute JavaScript Code
Fire when event result is :True
Fire on page load: ticked
Code: javascript:popupFieldHelp('277938589795252851','1545903379570909')
I appreciate any one who can tell me what i am doing wrong here or provide a solution to my problem of achieving to trigger the help window of a select item automatically.
Kind regards
CarlosHi Carlos,
I set up a test case in exactly the same way and it worked fine for me. I created a page item called P1_DA_DEMO and added some static select list values then added some help text. The settings I used are below, I suggest you try again but also make sure you have no other Javascript errors on the page. Use a tool like firebug to check.
Name : Dynamic Action Demo
Sequence: 10
Even: Click
Selection type: Item(s)
Item(s): P1_DA_DEMO <- a selection list item
Condtion: - No Condition -
True Actions
Sequence: 10
Action : Execute JavaScript Code
Fire when event result is :True
Fire on page load: Not Ticked
Code: javascript:popupFieldHelp('277938589795252851','1545903379570909')
Event Scope set a s Bind.
Thanks
Paul -
How to create list items with multiple attachment files using rest api javascript
In one of user form I am using javascript rest api to create a list item with multiple attachment files. So far I am able to create list item and once created uploading an attachment file. But this is two step process first create an item and then upload
a file.
It create an additional version of the item which is not desired. Also I am not able find a way to attach multiple files in a go. Following is the code I am using.
createitem.executeAsync({
url: "/_api/web/lists/GetByTitle('UserForm')/items(1)/AttachmentFiles/add(FileName='" + aFile.name + "')",
method: "POST",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
binaryStringRequestBody: true,
body: fileContent,
success: fnsuccess,
error: fnerror
So somehow I need to combine item attributes along with attachment files in body: param. I visited https://msdn.microsoft.com/en-us/library/office/dn531433.aspx#bk_ListItem but no success.
Appreciate any help.Thanks Mahesh for the reply and post you share it was useful.
But this does not solve the core of the issue. You are uploading attachments after creation of item and multiple files are being attached in loop. This is kind of iterative update to an existing item with attachments. This will end up creating multiple versions.
What I am trying to achieve is to create an item along with multiple attachments in a go. No item updates further to attach a file.
Please suggest how this can be done in one go. SharePoint does it when one creates an item with multiple attachment.
Thanks for your reply. -
How to find the font and replace another font using javascript in illustrator?
Dear All,
how to find the font and replace another font using javascript [batch process] in illustrator?
i have 700 image file, it very deficult replace one by one.
regards,
.Suresh.SAsk the creator of the file for a unprotected version.
-
Request help to display a list with parent and child list item.
I created a static list with items A,B,C and a child item A1 under parent A. I chose the template "vertical Side bar list". I am using theme 10 (sand) for my application. I created page 0 and am displaying the list on page template region position2. I am able to see the side bar with options A,B,C. But am not able to see the child option A1 when I click on Option A. I tried using 'DHTML MENU WITH SUB LIST' but When I click on option A, the child entry A1 is showing over the B and C options. I know this might be a pretty basic functionality. I am new to APEX and am just learning. I appreciate any help you give me.
Mr.Backstrom,
I have changed the list template overide to dhtml Tree. And now the list is being displayed as vertical unordered list with bullets. Is it possible to take off the bullets? Thank you for your time.
Suma. -
Workflow for creating new item and updating list
I believe that the answer is easy, but because I am already having trouble with this issue for few days I am getting blind to see the solution:)
I have two lists and a workflow running behind. Basically when new item is created in first list, workflow makes a copy in second list. Because this workflow works only when new item is added, I have a problem when item is updated, items in second list just
disappear - are empty. I believe that I have a problem with workflow, because somehow I should also have in to update list in case of change.
Please help.
Thanks in advanceHi,
According to your description, my understanding is that the workflow you created was not started when an item was updated in first list.
Did you check the option “Start workflow automatically when an item is changed” in SharePoint Designer?
Did you sign in as system accout?
Please use another list to check whether this issue occurs.
If this issue still occurs, please provide screenshot about the details of the workflow in order to find out what goes wrong.
Thanks,
Dean Wang -
How to create a multi column list item and select these values from a LOV
Hi all,
My requirements are:
1) create an LOV which holds the productno, productname and productprice fields (this is working)
2) at run time, select one record from LOV and populate the list/grid with this selected record values of productno, productname and productprice fields, so we are showing them on the form in the form of a table/grid (not working)
3) be able to select multiple records from LOV and be able to populate the list item with multiple records (not working)
4) have two more columns in the list/grid, for productquatity and total price (not wokring)
Please help me.
how can i create this grid or list in oracle
whats the possible way of acheiving this in oracleIf you use a list item to display multiple columns then you'll need to use a fixed-width font. You can achieve a similar look with proportional fonts by using a normal block and setting the fields' bevel to 'None'.
Each column in the LOV has a Return Item property (under Column Mapping Properties). Set this to a :block.item reference for each column to bring the data back into those referenced fields.
You can't select multiple records from an LOV. For this you will need to create your own form. Check the help for system.mouse_button_modifiers to see how to respond to Ctrl+click and Shift+click.
To add columns just modify the LOV's record group's query. -
Hi,
I have requirement in Sp Designer 2010,Get List item URL and insert in another list as one column value.When open another list and click on same item column entry url will show the parent item information.
Here i have create work flow and insert item URL in another list but cant find appropriate item url information.I can easily make item url link through String builder in mail body with using current id and predefine link,but
when try to insert the same type of item link in another list where i cant find string builder for create custom url link,only get valur of Path,URL,Absolute URL and Relative server URL,all these links or not provide me exact
item link dispaly information.
So I opened SharePoint Designer and start creating the workflow associated to the list.
As there is some Field from source related to current item URL I start using it
Encoded Absolute URL – this one should be the one to use
Server Relative URL
URL Path
Unfortunately, none of these options were providing the correct link. Indeed, these options are providing an incorrect path:
Encoded Absolute URL
http://wfe1/Lists/bpf/1_.000
Server Relative URL
/Lists/bpf/1_.000
URL Path
/Lists/bpf/1_.000
As you can see, the item URL is composed by an ID while it should be http://wfe1/Lists/bpf/dispform.aspx?id=1
Hasan Jamal Siddiqui(MCTS,MCPD,ITIL@V3),Share Point Application Developer,TCSUnfortunately, [%Current Item:URL%] doesn't seem to be available from a "Site Workflow" associated to a List. I'm finding less advantages to doing a "Site Workflow" when I don't necessarily need to. One problem is the workflow is initiating
twice. I'm thinking I should have just created the workflow as a a "List Workflow."
I am going to try "Association Columns" -- that may work. Anyone have other suggestions? -
How to read list item and display Title and on click hyperlink as value by javascript /jquery
on newform.aspx just above the top of cancel button I want to put 1 hyperlink "Help"
but I want to do this by script/jquery by reading my configuration list where 1 column is TITLE and other is- URL
in TITLE column will write "Help" and in URL column I will write
http://portal1234/sites/sudha/MyHelppage.aspx
so script should read Title and display Help--->1st part
Script should read Value column and on click of help-(display link) the respective url should be open in new window.-->second part
Please let me know reference code for adding anchor tag dynamically by reading from list
I can see hyperlink near cancel button-
$(document).ready(function(){
var HelpLinkhtml ='<a href="#" text="Help">Help</a>';
var position =$("input[value='Cancel']").parent("td").addClass('ms-separator').append(HelpLinkhtml);
now for reading from list I am trying below script-
$(document).ready(function() {
GetHelpLinkFromConfigList();
function GetHelpLinkFromConfigList()
//The Web Service method we are calling, to read list items we use 'GetListItems'
var method = "GetListItems";
//The display name of the list we are reading data from
var list = "configurationList";
//We need to identify the fields we want to return. In this instance, we want the Title,Value fields
//from the Configuration List. You can see here that we are using the internal field names.
var fieldsToRead = "<ViewFields>"+"<FieldRef Name='Title' />"+"<FieldRef Name='Value' />"+"</ViewFields>";
//comment
var query = "<Query>" +
"<Where>" +
"<Neq>" +
"<FieldRef Name='Title'/><Value Type='Text'>Help</Value>"
+
"</Neq>" +
"</Where>" +
"<OrderBy>" +
"<FieldRef Name='Title'/>" +
"</OrderBy>" +
"</Query>";
$().SPServices(
operation: method,
async: false,
listName: list,
CAMLViewFields: fieldsToRead,
CAMLQuery: query,
completefunc: function (xData, Status) {
$(xData.responseXML).SPFilterNode("z:row").each(function() {
var displayname = ($(this).attr("ows_Title"));
var UrlValue = ($(this).attr("ows_Value")).split(",")[0];
AddRowToSharepointTable(displayname,UrlValue)
function AddRowToSharepointTable(displayname,UrlValue)
$("#NDRTable").append("<tr align='Middle'>" +
"<td><a href='" +UrlValue+ "'>+displayname+</a></td>"
+
"</tr>");
<table id="NDRTable"></table>
Thanks :)
sudhanshu sharma Do good and cast it into river :)Hi,
From your description, you want to add a help link(read data from other list) into new form page.
The following code for your reference:
<script src="http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(AddHelpLink, "sp.js");
function AddHelpLink() {
var context = new SP.ClientContext.get_current();
var list= context.get_web().get_lists().getByTitle("configurationList");
var camlQuery= new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Help</Value></Eq></Where></Query></View>");
this.listItems = list.getItems(camlQuery);
context.load(this.listItems,'Include(Title,URL)');
context.executeQueryAsync(function(){
var ListEnumerator = listItems.getEnumerator();
while(ListEnumerator.moveNext())
var currentItem = ListEnumerator.get_current();
var title=currentItem.get_item("Title");
var url=currentItem.get_item("URL").get_url();
var HelpLinkhtml ='<a href="'+url+'">'+title+'</a>';
$("input[value='Cancel']").parent("td").addClass('ms-separator').append(HelpLinkhtml);
},function(sender,args){
alert(args.get_message());
</script>
Result:
Best Regards
Dennis Guo
TechNet Community Support
Maybe you are looking for
-
How to: username as default value in a form
How can I use the user_name (portal user: wwsec_person.user_name) as a default value in a form. When I use #USER I get the db_user value.
-
HELP ME IN MY JAVA PROJECT PLESE=(
i need help in my java programming.anyone who can help please email [email protected]
-
HT1695 Do I need to charge my ipad before setting it up?
Do I need to charge my ipad mini before setting it up? and if so how long?
-
How to change table name after creating page and application
Hi HTMLDB Team, i have created a application with page where the region use master detail form with table name emp.Now after developing the page and the application i want to change the table from emp to emp2 where emp2 is the table with same structu
-
Populating second select box on the basis of first.
Hello I want to populate second select box based upon the value selected in first select box from database.The second select box should be in disabled state first and should be enabled only if i select from first selct box. I want to make it by using