Requests


Post requests and questions in this post, but be patient awaiting reply or solution examples. This is a “one man blog” and i have limited time to answer questions. There will be less activity during the summer months, but i will keep posting new solutions, only on a slightly smaller scale.


I’m open to requests!
I get many ideas on things to write about from my readers, feel free to make requests on things you would like to learn more about.

I will, from the best of my knowledge (and time), answer your questions.

Post requests as comments to this post.

Updated!

Use the rating on the request to vote them up, thus “forcing” me to answer them…

The comments are split into pages with 25 top level comments per page, and the last page displayed by default. Use the links at the bottom of the page to read older comments.

987 thoughts on “Requests”

  1. First and foremost thanks for everything you have posted!

    As you know on all list views and document views, the view selector is on the right hand side of the menu bar. This can make it quite cumbersome for users looking at lists with many columns to change the view. A better option would be for the view selector to be on the left hand side and right hand side of the menu bar. I know I can move the view selector via SPD but would rather use a JavaScript options if one was available. Would this be something you would be interested in creating?

    Thanks
    tecrms

  2. Hi Alexander:
    Your work may be fun for you but it’s a gift for us. Thank you!

    A small item: I need to hide the “Check Names” and the “Browse” icons on a NewForm or EditForm “People-Picker”.

    Thanks-

    Charlie Epes

    1. Hi Charlie,
      This one is small enough to post directly here. The FieldInternalName of the field to hide these elements on is “Responsible”:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      // Hide "Check Names" and "Browse" icons on a NewForm or EditForm "People-Picker"
      $(fields['Responsible']).find('.ms-usereditor td:has(a)').hide(); 
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Alexander

  3. Hey Alexander,

    I currently have a MS Word based form that contains a 2 column by 10 row table where users provide up to 10 keycodes and their corresponding descriptions. I am hesitant to make 20 sharepoint variables to capture this since it will make a mess of the form – and I don’t need to query or report on these fields. Instead I’m looking for a possible solution for pre-populating a rich text field with a table template including column names. This way when a user creates a new item, they will see the familiar table and simply fill it in as per usual.
    Not sure if its possible but you have really amazed me so far so figured I’d ask =)
    Many thanks,
    Marc

    1. Hi Charlie,
      It was actually Paul Grenier who wrote the article. I had not thought about that solution – it was clever.

      I have tested his solution and rewritten it to adapt it to pop-up on mouse-over (floating), and to preview only selected values – like what you request. I will post it during the weekend (if i get the time…).

      Alexander

  4. is there a way to run an sql query and populate a sharepoint list? I have found myself going around my ass to get to my elbow with this. currently i have a sharepoint list as a linked table. I run a query in access to build another table, then run a macro to delete the SP list, another macro to make table in SP list. There has to be an easier way to pull data from a database and upload to SP.

    1. Hi Larry,
      I cannot help you with querying other resources than SharePoint lists. “My” queries uses SharePoint web services for the querying.

      Alexander

    1. What I believe to be a useable functionality would be that is has a way to click (the small space beween QL and Content) and drag to the width of user choice. A double here to close it completely, and a final double click on the left, where it has closed, to open back to the size set by the end user. all this also rememberd by cookies upon return to the site ( the defined width by user).

  5. Hi Alexander:

    Is there a way to hover over the Title field (or perhaps the Edit icon) in a default List view and have the EditForm pop-up so that the user can edit right then and there?

    Thanks-

    Charlie Epes

    1. Hi Charlie,
      I think it would be possible, but I’m not sure how elegant it would be, as the page would have to refresh to display the new information.

      Look at the preview-solution you requested above over the weekend and see if it can be adapted to fill your need.

      Alexander

  6. There are lots of actions that can be performed by Sharepoint when the conditions of a workflow are met such as sending an email to a user, deleting the item and updating a field of an item. But one thing missing is the ability for the workflow to send the item to a printer automatically. We have a list that we use to enter in sales orders and we would really like sharepoint to send the order to a printer when certain fields equal certain values. Is there a script that can be written to do this?

    1. Hi Matt,
      I do not have a solution for responding to a change made by a WF, but if the “final” change is made in EditForm, it’s no problem to open the Print Dialog from there.

      Alexander

  7. First off you rock! I have learned a lot by following your blog. The question I have is how could you re size the plain text fields so they don’t go the width of the form?

    This is something that plagues me and probably everyone else trying to customize those pesky forms.

    Also I am trying to figure how to get the quick launch horizontal instead of on the left of the screen.

    Thanks in advance.

    1. Hi Mark,
      The width of the text field (both single line and multi line) can be set like this:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      // Make object of all fields
      fields = init_fields();
      // Sets the width of the Title-field to 200px
      $(fields['Title']).find(':input').css({'width':'200px'});
      
      // Function to "objectify" all fields to be able to address them by their FieldInernalName
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7;
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      Alexander

      1. How can I add this function together with Dynamic Forms, cause I’d inserted in CEWP and on IE8 worked right, but on Google Chrome was not rendered

  8. Good Day Alexander, thanx for the shout out on the alignment.

    I ran into an issue today and I am lost. I am not sure how to handle it. I am building a form using a few of your scripts. It is an internal form for my company. Many people do not have admin access to their machine so I figured they could not turn off JavaScript. Well the project owner has JS disabled and I am not sure yet if they can enable it.

    My request: is there a way to display a message on the page that says JavaScript is disable, blah, blah , blah… without using JavaScript? almost like the old noscript tags used in html.

  9. New request. I ahve noticed at the end of each of your script there is a function “function init_fields()”. if implementation several of your script, can this be added to the page one time, at the end?

    1. I know your busy, so I just remove the beginning and ending part of all codes and placed it one time on thr page. appears to be working, will need more testing

    2. Hi,
      Yes, it only needs to be added once. In the top of the script like this:
      fields = init_fields();
      This makes an object of all fields which can be addresses by it’s FieldInternalName. Containing the “tr-tag” and it’s content for that field.

      The function can be added anywhere on the page or in an external file.

      Alexander

  10. Hi Alex,

    The script for resizing the text fields works perfectly.

    I have another request. I am trying to get my form to to display in tabs. The form has 40 fields and it needs to be split between 4 tabs like a wizard. Any help would be greatly appreciated.

  11. As if I dont make enough requests. lol Is there a way to create a view or list that display the sites List and Libraries, with a link back to them, if the permissions are inherited from the parent (this links back to the permissions of that list/library) and the date of last modified?

    So 3 columns, List/library Name, permissions inherited Yes/No, and dat Last modified. On a side note is there a way to make this a roll up, having this for each sub site, that roles up to the top level.

    1. Hi,
      Sorry, but i have no such solution. It is possible, I’m sure, but i do not – as for now – know how to do it.

      You could look at the web services sites.asmx and lists.asmx. The list of lists and document library’s should not be a problem, but the inheritance and lastmod, I’m not sure about.

      Alexander

  12. Hi Alexander:
    When a user attaches a document to an item in a List, the attachments are stored in a hidden document library with the List Item ID as the Library name. The user cannot get to the library, as one would get to a normal Document Library.

    Can you think of a way, from a List, to easily attach documents to a visible Document Library and then create and keep an automatic link to the List Item?

    Thanks

    Charlie Epes

  13. Hi Alexander:

    Is it possbile for you to create some code that would hide some of the toobar menu items such as New, Actions, Settings, Views or any of their sub menu selections based on a created permission level (Site Settings > Permissions > Permission Levels) ?

    For instance if I created a new permission level called “Director” which is tagged to a user or group, I would like for them to have tailored menu functions in a list or library based on this new permission level…hope this makes sense

    thanks.

  14. Good day Alexander, Todays request, amoung the many others :), is there a way to add a function (either by adding a button or an onchange event) that could clear (reset) a predefined set of fields? Example: I am using you script to dynamically hide/show groups of fields. Say today I have 3 groups I show and populate these fields. If somthing changes ion the project tomorrow and I only have 2 groups now, hiding the fields does not remove the field contents. I would like to add a button near the groups of fields that only removes that group of fields contents and does not touch any other part of the form.

    Can this be done?

  15. Hello Alexander,

    Firstly thanks for this terrific materal – you have a great gift for educating.

    Keping with the excellent discipline of maintaining a library of scripts in a SP library, is there a way to add an “open with” option to the file context menu so the scripts can also be edited in SP (using for example notepad++). Currently , clicking a .js file will try to execute it.

    This has uses elsewhere where the associated application is not on the standard list.

    cheers.

    1. Hi again,
      I do not think this is feasible because Notepad (and other non-office programs) is not compatible with check in/check out etc. I tried to edit the “OpenControl” for txt-files, but all i got was error messages…

      My best answer is to switch to “Explorer view” and do it from there.

      Alexander

  16. Hi Alexander:
    Is it possible to add a clickable “button” or icon next to a date picker that would insert “Today’s Date” into the field box?

    If this can be done on the NewForm and EditForm, that would be great. If this can be done on a DispForm or even in a list, that would be fantastic!

    I hope you are well-

    Charlie

    1. Hi,
      Here’s an example – it could be added some functionality for F=first, L=last. Let me know if that would be interesting.

      Update: Code moved here:
      Set datefield to first day of month, today’s date or last day of month

      I wonder why you Would like to have this in DispForm and a list? – please explain.

      Thank you for the mail you sent – I’m glad you enjoy this blog, and that you find the solutions useful. I will try to answer your other questions.

      Alexander

    2. Hi:
      I tried this on an EditForm and NewForm. I can’t seem to get it to work. It’s in a CEWP below the form and pointed to my JQuery 1.3.2 library. I need guidance.

      Thanks-
      Charlie

    3. Hi:
      The “date picker clicker” works perfectly! Thank you-

      Two things:

      1.) I’m not sure what you meant when you wrote:
      “…it could be added some functionality for F=first, L=last. Let me know if that would be interesting.”

      2.) If it’s possible to have this JQuery work on a DispForm and a List View, the user can click once and be done.

      Thanks-

      Charlie Epes

    4. I have trouble understanding how you want to use this functionality in DispForm and a list view. Could you describe what you want to achieve with this? (it is possible, but i do not see the full picture).

      Alexander

  17. Hi Alexander:
    I told a fellow SharePointer about your talent! Now I’m passing on her request.

    “We have a custom list with a lot of fields. I need to divide it into sections and then easily show/hide those sections. I am going to try dividing the form into div tags and then use jQuery to display the sections in either

    Tabs or an accordion (I’ll send you the email with the screenshots.)

    I’m just curious if, in all your SharePoint travels on the web, have you already seen this done anywhere? I’ve seen it done for a navigation menu but not for sections of an editform.”

    Thank you-

    Rebecca Waild

  18. Hi:
    Similar to the “Date Picker Clicker”, do you know if I could click a link and the users login name would fill a People Picker (person or group)?… on a newform or editform?

    Charlie Epes

  19. Hi:
    I haave users who are updating several date fields all week long and they are being trained to access the SP LList on the day that the action is completed. By clicking on a date field in a DispForm or better yet, a List view, the mouse-clicks are reduced greatly. In this case, speed is of the essence.

    Charlie Epes

    1. I have an upcoming solution for editing directly in a list view. I have to do some more testing and tweaking before it is released, but within the week it should be ready in v1.0.

      I have tested it with date columns and single line text for now. I may find a solution for editing more fields. For now it is designed for editing one “TD” at the time.

      Alexander

  20. I have a project staffing form with a Skills column that is a multichoice field. I’d like to be able to split the selected values into individual keyword (phrases) so that they can be passed into a hyperlink that creates a search query string, i.e, the selected skills are: project management, estimating, scheduling, and the desired search query should be SearchCenter/Pages/peopleresults.aspx?k=Skills: “project management” Skills “estimating” Skills:”Scheduling”

  21. Thanks for the great site.

    Wondering what the easiest way is on a standard share point form to prompt the user with a confirm alert (Ok, Cancel) to control whether or not the form is submitted?

    For example, when the user chooses Ok, they are then prompted to confirm if they are really sure they want to submit the form – if they choose Ok, then the form submits. If they choose cancel then nothing occurs and the user is able to continue editing data on the form (i.e. the form is not submitted)

    Thanks

    FT

    1. Hi,
      Add a CEWP below the list form in NewForm and EditForm. Insert this code:

      function PreSaveAction(){
        if(confirm("Are you sure?")){
          return true;
        }else{
          return false;
        }
      }
      

      SharePoint automatically executes any code in this function when pressing “OK”. It must return true for the save item to take place.

      Alexander

  22. Hi Alexander:
    A user asked me if it’s possible to have a button on a List View that, when clicked, would highlight the entire row. This way, the user would be able to flag items for specific review by another user.

    I suppose it would be necessary to have it be a click-on/click-off feature. Possible?

    Thanks for all your fine work.

    Charlie Epes

    1. Hi,
      I thought about this request as an addition to the “EditInListView”, by using a yes/no-column to toggle this highlighting.

      The issue with the one you link to is that it lives in the current page only – there is no write back. Therefore you cannot have on guy click on the line to toggle “follow up this item”, and another guy finding the highlighted rows.

      It has to be a write back action to manage this.

      Alexander

    2. An addition to the EditInListView would be great! My company doesn’t allow webmail access so I can’t even get to the WindowsLive account again. Oh well, I rather go with your solution! I never considered the writeback issue….

      Is it possible to broaden the EditInListView to “currency”?

      Charlie Epes

  23. I’ve got a list with columns that indicate individual’s status on certain days of the week. I’ve created views for each day of the week that only show the columns that apply to that weekday. Now I want a webpart that uses javascript to determine the current day of the week, then displays the view for that day.

    1. Hi,
      Here is a simple solution that reads the current day and redirects you to a view with that name:

      <script type="text/javascript">
      var objDays = {'0':'Sunday','1':'Monday','2':'Tuesday','3':'Wednesday','4':'Thursday','5':'Friday','6':'Saturday'};
      // Get daynumber
      var dayNr = new Date().getDay();
      // Get friendly name
      var dayFriendly = objDays[dayNr];
      // Get path
      var partRaw = window.location.pathname;
      var path = partRaw.substring(0,partRaw.lastIndexOf('/')+1);
      // Redirect if href do not contain "StopRedirect" - add this if you do want to stop the redirect: .../AllItems.aspx?StopRedirect
      if(window.location.href.indexOf('StopRedirect')<0){
      	window.location.href=path + dayFriendly + ".aspx";
      }
      </script>
      

      Add it to a CEWP in your view’s.

      If you add “?StopRedirect” to your url, you stop the redirect action (to let you edit the script without having to wait for the right day :-))

      Regards
      Alexander

  24. Hi Alexander:
    Thanks for the Tabs solution. I’ll try it this week.

    I had another thought/request.

    1.) Is it possible to wrap a List View of field headers and the data into two rows?

    ListView Example (before):

    Col1 Col2 Col3 Col4 Col5 Col6
    data1 data2 data3 data4 data5 data6

    ListView Example (after):

    Col1 Col2 Col3
    Col4 Col5 Col6
    data1 data2 data3
    data4 data5 data6

    Thanks-

    Charlie Epes

    1. Hi Charlie,
      Once again i must ask what you want to use this for… With one heading column, and one data column like you sketch, it will work. But if you add more rows in the form – how will users know which heading is for what field?

      Alexander

    2. Hi Alexander:
      On several of my lists, I struggle with the width of the page and too many fields. I use some simple javascript to wrap the column headers but I still need to prevent users from having to scroll side to side.

      My thought is that like-fields, such as date fields, could be clustered together, either on top of each other, or on a 2nd row.

      For example, another .Net application I use (which is similar to yours “today’s date picker clicker”) the stages in a process are stacked in 2 columns. I will send you a screenshot via gmail.

      Charlie Epes

  25. I really like your Tabs in SharePoint form you posted. Is there any chance that you might create a tab container that places webparts on the page into it? For maximum user could they be selected by webpart ID and not by the zone. This way more than one tab container could be placed anywhere are the page.

  26. Christophe’s Easy Tabs is an excellent webpart but it grabs everything within a webpart zone. What would be nice is to allow the selection of which webparts are to be placed in the tabs from the webpart zone. This will give one more ability to have more than one “Eays Tab” type webpart within a webpart zone.

  27. Hi Alexander,

    I would like to use your headings solution but in the displayform have one of my other fields display as text after the heading so:

    This is a heading – this is a field.

    Would this be possible?

    Thanks

    Andrew

  28. Hi Alexander,

    I mean when the headings appear in the dispform I would like one of the fields to appear alongside it. So a text field is displayed against the heading.

    Thanks

    Andrew

    1. Hi Alexander

      This is what I am after but I wanted it to be shown against a field used for your headings article but obvisouly this hides the field on the form and just shows what you have in the field for example:

      #H#17#880077#Outcome

      What I would like is an internal fields contents to be shown after the outcome text before in the DispForm.

      Thanks

      Andrew

    2. Hi Alexander,

      Sorry if I seem to be confusing you. What I have at the moment is a heading created by your headings article which is called ‘OUTCOME’. I then have another field called DESCRIPTION which text is entered in to.

      In the Display Form I would like the contents of the DESCRIPTION field to show alongside the OUTCOME heading. For example it would look like the following in the form:

      OUTCOME — contents of DESCRIPTION
      next field
      next field
      next field

      If you still do not understand then please let me know and I could provide you with screenshots.

      Thanks

      Andrew

    3. Is this beginning to resemble what you are after?
      Before

      After

      Script

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/HeadingsInSharePointLists.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      showHeadings(200,false,false,false);
      
      // Get the HTML from the Description field
      var descrHtml = $(fields['Description']).find('.ms-formbody').html();
      
      // Hide the "Description-field"
      $(fields['Description']).hide();
      
      // Insert the HTML from the Description field in the "formbody" of the "HeadingOutcome"
      $(fields['HeadingOutcome']).find('.ms-formbody').html(descrHtml);
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Alexander

  29. Hi Alexander,
    I would like to ask you for help, regarding setting a people picker field to be read only on EditForm. There are 4-5 people picker fields and i have nicely implemented the script to hide the checkperson and browse buttons, it works great thanks, but now i need to make those fields Read Only and they are filled with values. I have already tried with a script to find elements and hide the people picker field by the title element but it works only for the first people picker field, not for the rest of the form. Any help is welcomed.

    Thanks,
    Esad

    1. It does the job, makes the field read only but it also swaps from display name to account name and am running from this issue.
      Is there any way to make the people picker field read-only but also to retain the Display Name in that field instead the account name.

    2. Hi,
      Which browser do you use? In my setup it does what you want. If you send me the code by e-mail, i can look at it (not the fieldutility.js).

      Alexander

    3. Hi Alex, sorry for the late reply, holidays:)
      I am using IE7, and i got it fixed somehow 🙂 Thanks a lot Alex, i drink my coffee and check your website almost every day.

      I do have another question if it is appropriate to ask in this post, and it is regarding how can i check if attachments are present on NewForm, and if not to push an alert. I know the PreSaveAction function does simular job, but have no idea for attachments.

      Thanks again,
      Esad

    4. Try this code:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      
      function PreSaveAction(){
      	if($("#idAttachmentsRow td.ms-formbody img").length==0){
      		alert("You must add an attachment before you can save this element...");
      		return false;
      	}else{
      		return true;
      	}
      }
      </script>
      

      Alexander

    5. Works like a charm. Attachments in sharepoint item are a must have now thanks to you. Dunno why MS doesn’t include it as an option already.

      Thanks Alex,

      Esad

  30. Hi Alexander,

    I am not sure if you have recieved this request before, but it is related to this website, not a javascript request. I was wondering if a “Table of Contents” could be added in addition to the forward/backward choices at the top. Perhaps this already exists somewhere and i missed it. I love this site and look at it often, but i’d love to be able to go directly to an entry.
    Thanks for all of your hard work (and generosity in sharing!)
    Tasha

    1. Hi,
      I agree with you, it would be nice to have a complete TOC of all posts, but I have not found any plugin available in WordPress that provides this.

      It would have to be a manual job making this list… I will look into it if i find time.

      Regards
      Alexander

  31. Hi Alexander I am trying to perform the accordion with the Jquery UI. It works if I do it in a New, Edit, Display form. but when I try to create a single item form in SPD I am having no luck. Any assitance would be greatly appreciated.

    1. Thank you Chris,
      My problem here is that my blog is hosted at wordpress.com, and i cannot upload custom plugins… I might move the blog to my own server later on, and then it can be used.

      Regarding the “visible to” – problem, just send me the code to look at, and i will try to help. You find the address in the “About” page.

      Alexander

    1. Hi Alexander

      I have used the code but can’t seem to figure out which are the vital bits of code I need as it seems to mess up my dynamic expand fields in my form. If you would point the code out that would be very useful.

      Thanks

      Andrew

  32. Hi Alexander,

    I am trying to put some jQuery script into an EditForm but when I add the CEWP, the page gets locked into ‘edit’ mode. The site in question has Publishing switched on, and I believe this is the problem. Have you come across this issue and, if so, do you know of a workaround?

    Many thanks

    Stuart

    1. Hi,
      Are you sure you haven’t forgot to remove the “toolpaneview=2” from the url?

      If not i have not seen it before and have no real solution.

      Alexander

  33. Good day Alexander,
    I believe I have a simple request. I have found that some of my user have disable scripts in IE. In a CEWP I added noscript tags and in the no script tags I put a message to enable scripts and added css to hide the form. either my css is incorrect or this cannot be done. My request is I need a noscript way to dynamically hide the list form until user enables their script. here is my css. maybe I have id’d the wrong list form webpart.

    #MSOZoneCell_WebPartWPQ1 {
    display:none;
    }

    1. I have tested this several ways, and this works on my machine, but for some reason there are users that when they access the page the scripts dont run but they still see the form. do you know of any reason why this might happen. My script library is local and all users and domains have access.

    2. I think identified the issue but still no luck on fixing it. I found some users are on IE 6. I am not sure how to make the script work for IE 6. Any thoughts?

    3. I have no experience using noscript tags, but is it the script or the css that does not work in IE6?

      How does SharePoint act when browsed with scripts disabled? I would guess it did not work as expected?

      Alexander

    4. the no script tag allows you to provide text for users that have scipt disabled. When I disable the sciript in my browser it works. These other users have something else. I noticed they are using IE6, and had a different security setting, but I have not been able to identify what the different is because I do not have access to their machine. when i run IE6 it works perfectly, so I know it is not you script or how I implemented it. I also confirmed that their scripting setting were set to enabled which really throws me off. I have no clue what security setting disabled causes this.

  34. Hi Alexander

    Is it possible to be able to move the OK and Cancel button to the left hand side in the New, Edit and Display forms?

    Thanks

    Andrew

    1. Hi, This is the answer to the first question.

      Add a CEWP below the NewForm, DispForm and EditForm and add this code:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      $("table.ms-formtoolbar td").each(function(){
      	if($(this).attr("width")=='99%'){
      		$(this).prependTo($(this).parent());
      	}
      	else if($(this).find("td input[id$='GoBack']").length>0){
      		$(this).prependTo($(this).parent()).after("<td class='ms-separator'>&nbsp;</td>");
      	}
      	else if($(this).find("td input[id$='SaveItem']").length>0){
      		$(this).prependTo($(this).parent()).after("<td class='ms-separator'>&nbsp;</td>");
      	}
      }); 
      </script>
      

      Alexander

    2. And this it the answer to th second question:

      Add a CEWP below the NewForm, DispForm and EditForm and add this code:

      <style type="text/css">
      	.ms-formbody_mod {
      	background:#E3170D none repeat scroll 0 0;
      }
      </style>
      
      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      // Add red background to the  formbody of the field "Description"
      $(fields['Description']).find('.ms-formbody').addClass('ms-formbody_mod');
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;	
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7; 
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      Alexander

  35. is there a way to view all whether permissions are inherent or not in a document library. a script that can convert a calculated field to view all at once so dont have to click each individual item

    1. Hi,
      I do not think so, as the permissions are checked when interacting with the element. If anyone has some information on this, please share it.

      Alexander

    1. Hi Alexander:
      I figured it out using JS:

      // <script type="text/javascript">
      
      function hideSum(myString) {
      var docTags;
      docTags = document.getElementsByTagName("B"); 
      for (var i=0; i < docTags.length; i++) {
          docTags[i].innerText = docTags[i].innerText.replace(myString,""); 
          } 
      }
      
      _spBodyOnLoadFunctionNames.push('hideSum("Sum =")');
      </script>
      

      Charlie

    2. Hi Charlie,

      I tried this code in a SP2010 list, but it’s not working. My SP list is on a sitepage with a graph webpart. What can be wrong?

      Thanks,

      Jimmy

  36. Hi again:
    My next question: Do you know a way to capture the Total’s (ms-vb and/ or ms-vb2) and place them into a CEWP to create a simple KPI or data summary grid?

    Thanks-
    Charlie Epes

  37. I have been unsuccessful trying to auto populate fields. using your script get user information wss, Is there a way to write the returned data to fields in sharepoint, either through a click event or on page load (page load perfered)? I have a survey for managers. I need their subs to submit the survey and then roll up the averages to each manager. I do not want the user to have to click their name and their managers name, it is suppose to be anonymous. I know wss does not have manager names in the user profile, maybe we can do a lookup on an external list. auto populate user name in a people picker field, this field does a lookup to external list and auto populate managers name in a second people picker. can this be done?

    Auto popuplate user in people picker field?
    auto populate other information for other fields from external list base on previous people picker?

    1. Hi,
      I believe this is related to this question.

      Read the answers here.

      In general, it could be done like this for a Text-field:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      // Find the Title-field and insert text
      $(fields['Title']).find('input').val("Insert this text in the Title-field");
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Alexander

    2. Finally made it back to this one. Got it working, trying to implement on people picker. input.val not working. Can you provide the text to change on line 5 for setting a people picker val. I know you have the script with the click event. And using that script I could auto populate the field. I was hoping for a single line, set field val like above.

    3. Hi,
      Replace line 5 with this:

      $(document).ready(function(){
      	setPeoplePicker('MyPeoplePicker','domain\user'); // note the double backslash
      });
      
      function setPeoplePicker(FieldInternalName,newVal){
      var field = $(fields[FieldInternalName])
      	if(field.find('.ms-inputuserfield:visible').length>0){	
      		// IE
      		field.find('.ms-inputuserfield').html(newVal);
      		field.find('img:first').click();	
      	}else{
      		// FF
      		field.find("textarea:first").val(newVal);
      	}
      }
      

      Alexander

    4. I was so close. there is a small bug. In WSS when the form load, with the new script, the menu (top right) for my settings opens.
      do you know what might trigger that.

  38. Hello Alex,
    I’ve been trying to make a report out of a list but with multiple-filter choice fields that a user selects them and pushes it in the URL string. It works good only when you need two values, but if you want to add another value and then select only two out of the three… and i am stuck.

    Any ideas how to make the list to be filtered via multiple options buttons.

    I like the new post for the workflows, will implement it.
    Regs,
    Esad

    1. Hi,
      Is it a string like this you are building:

      AllItems.aspx?FilterField1=LinkTitle&FilterValue1=Dodge&
      FilterField2=Model&FilterValue2=Charger&
      FilterField3=Color&FilterValue3=Black

      If so, you have to make a function to build the string so that you do not get “holes in the numbering sequence”.

      If the user only selects the filter for “Model” and for “Color” the FilterField3 and FilterValue3 must shift to FilterField2 and FilterValue2.

      Alexander

  39. [16.01.2010: Edited by Alexander to fix the codeview]
    Maybe this time I can post something we can get to work. I have been trying to peice together several scripts, including yours to make the multiple line text fields expandable. I found a workiong script but it only worked on plain text. I am trying to modify it to work on rich text. When i add your script for fieldinternalname I can at least see the image under the rich text box, but it does not work. using the new script I can not get the plain text to work. this is the link to the jquery plugin for textarea resizer
    http://plugins.jquery.com/project/TextAreaResizer
    here is the script I am trying to modify

    <script type="text/javascript" src=/sites/globalmp/JavaScripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery.Textarea_Resizer.1.0.4.js"></script>
    <script type="text/javascript">
    fields = init_fields();  
    $(fields['Comments']).find('input').TextAreaResizer();
    
         // Begin Original code
    	/* jQuery textarea resizer plugin usage */
    	//$(document).ready(function() {
    	//$('textarea[title="Comments"]').TextAreaResizer();
            	//	});
         // End Original Code
    
    function init_fields(){  
       var res = {};  
       $("td.ms-formbody").each(function(){  
           if($(this).html().indexOf('FieldInternalName="')<0) return;  
          var start = $(this).html().indexOf('FieldInternalName="')+19;  
          var stopp = $(this).html().indexOf('FieldType="')-7;  
          var nm = $(this).html().substring(start,stopp);  
          res[nm] = this.parentNode;  
      });  
      return res;  
    } 
    </script>
    <style type="text/css">
    div.grippie {
    	background:#EEEEEE url(/sites/globalmp/images/grippie.jpg) no-repeat scroll center 2px;
    	border-color:#DDDDDD;
    	border-style:solid;
    	border-width:0pt 1px 1px;
    	cursor:s-resize;
    	height:9px;
    	overflow:hidden;
    	}
    .resizable-textarea textarea {
    	display:block;
    	margin-bottom:0pt;
    	}
    </style>
    

    the image is just a bar at the bottom of the field.

    Can we get this to work with internal name?
    can we get this to work on rich text field?

    1. Hi Larry,
      There is no problem making the “Multiple lines of text – Plain text” expandable, but making the Rich text ones expandable proved to be more challenging…

      It took me some time to figure it out because the Rich text multi lines are made up of iframe’s and does not like being messed with.

      I have the solution mostly finished, but i will test it a bit more to eliminate a few possible bugs before posting it.

      It will be ready during the next week.

      Regards
      Alexander

  40. In addition to my previous request. I need to convert my view from horizontal to vertical. I think this should be easy enough. In my view I want to do an average. 12 questions with numeric responses. how can i get the averages vertical also.
    currently we have by default
    q1 q2 q3
    score score score

    What I need to do

    q1 – score
    q2 – score
    q3 – score

    is this possible?

    1. Almost, so close. All I really need are totals. I dont need individual row items. In fact I want to hide all row items and average my grouped scores. Can that be done in that preview pane, pull in multi rows and return a total or average?

  41. Hi Alexander:
    Do you know of a way to change the “tilt” of a field or column header in a List to verticval or diagonal?

    T
    h
    a
    n
    k
    s

    Charlie Epes
    Buffalo, NY

    1. css is the easiest way
      [sourcecode language="language="javascript"]

      .ms-viewheadertr td, .ms-viewheadertr a {
      writing-mode: tb-rl;
      filter:fliph flipv ;
      vertical-align:center;
      /*text-align:center;
      text-wrap:normal;
      LAYOUT-FLOW: vertical-ideographic;
      word-wrap:normal;
      text-align:center;
      writing-mode: tb-rl;
      direction: ltr;
      filter:flipv fliph;
      white-space:normal;
      white-space-collapse:collapse;
      width:55px;*/
      white-space:normal;
      white-space-collapse:collapse;
      /*color: black !important;*/

      }
      .ms-menuimagecell, #imnhdr0 {
      display:none;
      }

      [/sourcecode[

    2. Here is one method:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      $(".ms-viewheadertr th[class^='ms-vh2']").each(function(){
      	colHeader = $(this).text();
      	newColHeader = '';
      	for(i=0;i<colHeader.length;i++){
      		newColHeader += colHeader.charAt(i) + "<br>";
      	}
      	if($(this).hasClass('ms-vh2-nograd')){
      		$(this).html(newColHeader);
      	}else{
      		$(this).find('a').html(newColHeader);
      	}
      });
      </script>
      

      Add this code to a CEWP below the list view.

      Alexander

    3. Use this for diagonal layout:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      $(".ms-viewheadertr th[class^='ms-vh2']").each(function(){
      	colHeader = $(this).text();
      	newColHeader = '';
      	padding = 0;
      	for(i=0;i<colHeader.length;i++){	
      		newColHeader += "<div style='padding-left:" + padding + "'>" + colHeader.charAt(i) + "</div>";
      		if(colHeader.charAt(i)==' '){
      			newColHeader += "<br>";
      		}
      		padding += 15;
      	}
      	if($(this).hasClass('ms-vh2-nograd')){
      		$(this).html(newColHeader);
      	}else{
      		$(this).find('a').html(newColHeader);
      	}
      });
      </script>
      

      Alexander

  42. Hi there,

    I just came across your site and wanted to say thanks for all the great articles. I don’t recall seeing an article referring to what I am looking for, so I thought that I would try to explain and see if there is a solution that you know of. I have a vendor contact form where enter the company, name, phone and a list of services that they provide (choice from a lookup column that allow multiple values). What I would like is to have is a view that would have each of the individual services listed and then list the vendors that provide that service. So a vendor might be displayed more than once if they provide multiple services. It would be similar what the yellow pages would display. For example the input would be
    ACME Corp Electrical; Plumbing
    Sunrise Co. Plumbing; Heating
    Zap Enterprise Electrical

    Output would then be
    Electrical
    ACME Corp
    Zap Enterprise
    Heating
    Sunrise Co.
    Plumbing
    ACME Corp

    Group by does not work with lookup or choice fields.

    Any ideas would be greatly appreciated.

    Thanks,
    Scott

    1. Hi,
      I’m sorry, but i cannot think of a solution with a standard list view. It may be possible with an XSLT dataview (this is not my best area), or it could possibly be done with a custom made “list view” created with javascript and CAML-query.

      You could then first query the “lookup source list” for all services, and then loop trough all services querying the list of vendors for which is providing the service – building HTML from the result.

      I cannot give you anything more right now, but this may be looked at later on – very busy right now…

      Regards
      Alexander

  43. Hi Alexander:
    I am wondering if it’s possible to reorder the (.ms-gb2) 2nd “group by” field of a List view by ascending or descending “count” order, instead of Alpha (if it’s people).

    ms-gb = month
    ms-gb2 = person

    Total is set to count items.

    In my example, I would like to see the person with the most item “count” at the top and the others below him.

    January
    John (22)
    Mary (19)
    Alexander( 18)
    Charlie (15)

    Thanks-

    Charlie Epes

    1. Not sure if this got a response but I have resolved this by creating a calc column the add numerical value to month (01) January. That group by the calc. In my requirements I added year also because next year is different than last year.

  44. Hi Alexander

    Would it be possible to pop up a dialog box when a Yes/No field has been selected to Yes with a message and an ok button?

    Regards

    Andrew

    1. Hi,
      Like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      fields = init_fields();
      // Yes/No field with FieldInternalName "AlertMe"
      $(fields['AlertMe']).find('input:checkbox').click(function(){
      	if($(this).attr('checked')){
      		alert("You checked it!");
      	}
      });
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Add to CEWP below NewForm or EditForm.

      Alexander

  45. Hello Alexander,

    I have reorganized my form in 3 tabs schema and it´s working great, but at the second tab I have an specific concern:

    I have 5 fields in the second tab but I would like to have the option to add a button below these fields that when I click this button would be possible to add 5 extra fields like the fields that I already have( I believe that they should have different names to not have a problem) and also an “x” or “remove” button to remove these 5 fields that I added there, like if I have created I new form clicking in a button, do you know what I mean?

    My first idea was “ok I can do that integrating an ‘accordion’ in a tab”, so in each accordion part I´ll have the 5 fields. I tried to do that but I didn´t have sucess

    I don´t know what can I do for solve that, is like if I already the fields in a hide situation and when I click in the button field they appear. I have a page in a intranet that has that and it´s a javascript solution that loads a jQuery library, could you help me with that?

    Thanks

  46. Hey a simple request

    Is there a way to remove or hide the Ok/Cancel buttons only the ones from the top from a NewForm.aspx?

    I wanna to keep the ok/cancel from the bottom and just remove or hide the ok/cancel from the top, is it possible do that without using Sharepoint Designer?

    My main concern is that the ok/cancel buttos from top and from bottom has the same value and if you apply the code in one will reflect in another

    Thank you very much

    Renan

    1. Like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      $("input[id$='SaveItem']:first").hide();
      $("input[id$='GoBack']:first").hide();
      </script>
      

      Alexander

  47. Is there a way to create an anchor within a NewForm or EditForm? I have a long intake, or it could be long. When I assign the the item to an owner and provide them a link to the form, it would be easier to have an addition to the link with the anchor that links to a specific field in the form. Maybe a script that uses the fieldinternalname and converts that to the anchor name for simplicity.

    1. Good Request Cookie:

      I have often wanted to find a way to add “Bookmarks” to SP forms for that very reason… much like you can bookmark a Word Doc or PDF to specific regions of the page.

      My need would require that I place links to each of the bookmarked form sections into a CEWP at the top of the form’s page so the user can skip right to the section he/she wants.

      Charlie Epes

  48. I have been thinking about another possible request. I like your text to choice script pulling the items from a source list. is there a way to expand this so that the dispaly value is different than the return value? Like a standard select field you can have the display value something easy to read, but the value returned may be a number or a shorter version of the label. Maybe the source list has two columns, display column and a return value column. Almost like the yes/no field where that returns a number, but the user is selecting yes or no.

  49. Hi Alexander

    You are da man!! Thank you for the education, would there be a way in the new form of a list to populate the multiline text box with a default value, a html table etc….

    Tony

    1. Hi,
      This code is for a list with three fields, one plain text multi line, one rich text multi line and one enhanced rich text multi line: FieldInternalNames: Plain, Rich and Enhanced. Adapt the reference to jQuery as needed:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      if(typeof(fields)=='undefined')fields = init_fields();
      
      setMultilineFieldValue('Plain','This is the value...');
      setMultilineFieldValue('Rich',"<div style='color:red;font-size:large'>Rich text</div>",true);
      setMultilineFieldValue('Enhanced',"<div style='color:red;font-size:large'>Enhanced rich text</div>",true);
      
      
      function setMultilineFieldValue(fin,strVal,pageload){
      var item = $(fields[fin]);
      	if(item.html().indexOf('FieldType="SPFieldNote"')>-1){
      		if(pageload || item.find('.ms-rtetoolbarmenu').length==0 || (!browseris.ie5up || !browseris.win32 || IsAccessibilityFeatureEnabled())){
      			item.find('textarea:first').val(strVal);
      		}else{
      			item.find('.ms-rtelong').contents().find('body').html('<div>' + strVal + '</div>');
      		}	
      	}else{
      		alert("The field "" + fin + "" is not a multi line field.");
      	}
      }
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7;
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      Alexander

    2. [moved by Alexander]
      Sorry man added this to a CEWP and cant get it to work…..

      The location is right because I have used it before, the internal name is from the source (I may of typed it wrong here)

      Anything I am missing?

      I call it using:

      setMultilineFieldValue(‘Enhanced’,”Enhanced rich text”,true);

      Besides the location of the library I changed the following

      item.find(‘.ms-rtelong’).contents().find(‘Request_x0020_Description’).html(” + strVal + ”);

    3. [moved by Alexander]
      sorry context would be good the previous post refers to setting a default value to aehnaced multiline text box

      I used your code as is just changing where i found the scripts and changed body to internal name of my field

      Eliminated first 2 calls to function because we are only using enhanced and finally added this code to a cewp

      Cant get it to work….UGH I am stupid ur a god, I am ugly ur good looking etc….

      SORRY!!

    4. Hi tecrms,
      The hyperlink field is nothing else than two input fields. Populate them like this:

      $(fields['MyHyperlinkField']).find('input:first').val('https://spjsblog.com');
      $(fields['MyHyperlinkField']).find('input:last').val('SharePoint JavaScripts');
      

      Alexander

    5. Alexander
      While the text fields work correctly,

      $(fields[‘MyHyperlinkField’]).find(‘input:first’).val(‘https://spjsblog.com’);
      $(fields[‘MyHyperlinkField’]).find(‘input:last’).val(‘SharePoint JavaScripts’);

      Crashes the page and I have to remove the CEWP. I then tried your basic script for filling in a text box with the following and it still crashed the page.

      // autopopulate a field

      fields = init_fields();
      // Find the Title-field and insert text
      // $(fields[‘Title’]).find(‘input’).val(“Insert this text in the Title-field”);

      // Use the following to set HyperlinkFields

      $(fields[‘MyHyperlinkField’]).find(‘input:first’).val(‘https://spjsblog.com’);
      $(fields[‘MyHyperlinkField’]).find(‘input:last’).val(‘SharePoint JavaScripts’);

      function init_fields(){
      var res = {};
      $(“td.ms-formbody”).each(function(){
      if($(this).html().indexOf(‘FieldInternalName=”‘)<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }

      Any thoughts?

      Thanks!

      BTW MyHyperlinkField is the name of the Hyperlink field in my test list

    6. Some control questions:
      Is it a unmodified form?
      Yes, I started with a new library and only added the hyperlink column.

      Is the CEWP placed below the form?
      Yes

      Does it work in another testlist?
      Yes, It does work with a list form, but I am using a document library list form and that must be the problem.

    7. Hi,
      I have tested in a DocumentLibrary with this code:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      if(typeof(fields)=='undefined')fields = init_fields();
      
      $(fields['MyHyperlinkField']).find('input:first').val('https://spjsblog.com');
      $(fields['MyHyperlinkField']).find('input:last').val('SharePoint JavaScripts');
      
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7;
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      The hyperlink Field is set.

      Is there any other code that interferes?

      Alexander

    8. Your code is working now. The only difference I can see it the line >> if(typeof(fields)==’undefined’)fields = init_fields(); mad

      The only problem I have now is:

      if I update the hyperlink to some other path it resorts back to https://spjsblog.com

    9. This code only updates if the field is empty:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      if(typeof(fields)=='undefined')fields = init_fields();
      
      var link = $(fields['MyHyperlinkField']).find('input:first');
      var description = $(fields['MyHyperlinkField']).find('input:last');
      
      if(description.val()==''){ // Checking the description as the link has a default value of http://
      	link.val('https://spjsblog.com');
      	description.val('SharePoint JavaScripts');
      }
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7;
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      Alexander

  50. I am trying to create an accept terms script. I have a doc library and an Accept Terms list. When you enter the doc library I need the documents hidden and the list form for accept terms visible until user selects “yes” they accept the terms. 2 things need to happen. The accept terms intake is now hidden and the library is visible. I need the accept terms intake to have that electronic signature. Of cource if there is another way I am open to that. I also need to have the accept terms intake visible when the user has not accepted the terms. Something like I trigger a workflow to check back in six months and reset the field to force the user to accept the terms again. List form visible, doc library hidden.

    1. Hi,
      Interesting request. I will make a note of this one and try to come back with a solution. I cannot guarantee anything, but stay tuned and it may appear!

      Regards
      Alexander

    2. I started working on this. I had my document library. I created a custom list with one field Choice Yes/No (required) and allowed content types so I could hide the title field. On the NewForm for accept terms I added CSS and Alexanders script to hide everything on the page but the one choice field and one set of ok, cancel buttons. I believe this would give an easy way to track initial accept. then your workflow can can run in the back to set your reminders.

      In my document library I add a page viewer webpart, linking to my Accept terms NewForm. I am not 100% happy with this setup, but this is where my skills took me. Currently I ha a view with the doc lib at the bottom and accept term newform at the top.

      I am working are trying to only show one of these at a time. default to NewForm until user accepts terms. May take me a little longer than Alexander, but it is a start.

  51. Hi Alex,
    I would like to ask you for help arround a big issue with keep session alive. I have appraisals done in sharepoint and the session timeouts on 10mins. To fix it i implemented a solution in an iframe “opening” a page on every 3 minutes, which in a way pings the server for a request. Now that works nice, except if the end user hits the save button in the same time as the script reloads/pings the server. Is there any way to implement anything to disable the save button before the page reloads and enable it after reloads.

    I can’ enable bigger timeouts on the web app due to resources/RAM issue.

    Regs,
    Esad

    1. You can disable the OK-button like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      
      function okButtonDisabled(disabled){
      	$("input[id$='SaveItem']").attr('disabled',disabled);
      }
      
      </script>
      
      <a href="javascript:okButtonDisabled(true)">Disable OK-button</a><br>
      <a href="javascript:okButtonDisabled(false)">Enable OK-button</a>
      

      Alexander

    2. Yes I got it to work but I have a issue. I am populating the field with a query string value, I can see the value populated, but when I save the item, no value in the field. Have can i make the field read only, but have it save the populated value?

  52. Hi Alexander,

    First off you rock! The Field side by side script was great.

    I have a request. I have registration form and at the top it has an attendee section. I have it defaulting to the following three columns:
    First Name
    Last Name
    Email

    Is there a way to have a plus sign so that they can add additional attendees if needed.

    Thanks in advance

  53. Wow, you get a lot of responses! Well, here´s one more. Have you tried to prefill a value in field control in a page layout? Or if you got an SharePointWebControls:RadioButtonChoiceField, that builds of a choice column, let say you have alternativs in the column and want to render the page with one of the alternatives. Another thing like this would to populate todays date in a datecontrol. Alexander, have you tried this?
    Best from Christian

    1. Hi, thanks for your quick reply. First, if I have a content type that connect to a global column and this column is a choice (with checkboxes).

      Then i use this in some page layout as a field control, and in SPD into the code among HTML (no dataview with xslt), the SharePointWebControls will be visible. This one I would like to modify like I can do with a SP list. I have try to modifiy this with Js with no luck yet, it seems to be different compared to ‘normal’ modifications with lists.

      Drop me a mail if you like, I will send you some screencaptures that explains more exact.

      Keep up your great work, thanks!

  54. First, great site. I can use a lot of these tips on my current projects. Have you thought about using more categories in your posts so it would be easier to browse? Just an idea!

    Do you have an ideas on how to remove “empty/blank” items when using the “group by” feature? See the example below. In other words, for category ‘Test 1’ you have to expand the blank item just to see the documents since they don’t have any subcategories assigned to them.

    Example:

    * Category: Test 1
    * Subcategory 1:
    – Document 1
    – Document 2
    * Category: Test 2
    * Subcategory: SharePoint
    – Document 3
    – Document 4
    * Subcategory: CRM
    – Document 5
    – Document 6

    This is how I want it to work:
    * Category: Test 1
    – Document 1
    – Document 2
    * Category: Test 2
    * Subcategory: SharePoint
    – Document 3
    – Document 4
    etc.

    Thanks!
    Kale

    1. Hi,
      I have had many requests for easier overview of the posts… I will try to add some more categories.

      Regarding your request it may be possible, but would require the script to “click” on the empty subcategory to load all the items, then remove the heading. I will add this to the “queue” and see if i can give you an example.

      Regards
      Alexander

  55. Hi Alexander,

    I’ve got a request about the possibilty to rollup events in a Gantt-view of a calendar.
    The Gantt-slider (http://www.pathtosharepoint.com/Gantt/default.aspx) is a nice thing to have but all items are listed. I like to group the events by user name to show all planned holidays per user over the year.
    Is there a way with javascript to be able to do that?
    Thanks for your attention!

    Regards,

    Stefan

  56. Hi Alexander:
    Is it possible for a Lookup field’s choices to show as Radio Buttons or Checkboxes on a form, instead of the usual drop-down?

    Thanks-

    Charlie

    1. Hi Charlie,
      It is possible for single lookups, but the lookup controls are rendered differently depending on the number of returned items (below or over 20 items). This is for single lookup’s and would work with radio buttons only.

      The multi-lookup is another, more complicated issue.

      I cannot help you on this right now, but might come back to it later.

      Alexander

  57. Boy you have your work cut out for you. Hope you are not getting overworked.

    I am trying to figure out a way to count unique visits to a single page in a single day. Is there a way with jquery that can look at the UserProfile, identify the user on first visit, and tally all unique visits during the day?

    On a grander scale, can the numbers or tallies be written to a list that tracks counts for multiple pages, by unique users?

    1. Hi,
      This would be possible. The “result” would have to be written to another list by a javascript-function.

      Each page that is “counted” must be fitted with a CEWP with a script.

      If i do this – would you prefer one line added to the “counter list” for every visit, or one line adding up all visits and presenting as a number in a column?

      Alexander

    2. Initially I was thinking that one line with count would be the best, but after thinking I believe it would be easier to just create a new line for each visit then can sort and group. This would also allow for other information like User, referring URL etc..

    3. In my search I actually came across a SP WebPart that does almost exactly what I am trying to do. The major issue with this is it needs to be installed on the server and thats not happening here. The functionality seemed to be simple. Had a list with several columns. thatbe updated by alll groups and permission levels, including visitors and it displayed a counter on page.
      http://hitcounter.codeplex.com/
      Too bad this is not a web part I could install with a simple upload.

  58. Hi Alex 🙂

    Hopefully you will laugh at this one, I would like to add to the right of the field a verbage/icon that you can click on and get help not mouse over

    As simple as opening a new page with info thats it….

    For example click here for help and its opens a new window with explaination

    Tony

    1. Hi Tony,
      No, not stupid… Do it like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      $(fields['Title']).find('.ms-formbody')
      	.append("<div style='float:right'><a href='https://spjsblog.com' target='_blank'>My link</a></div>");
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;	
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7; 
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      “Title” in line 5 is the FieldInternalName of he field to append the link to.

      Alexander

  59. Hi Alexander

    How do you create the drop down toggle script to work if you have one drop down field that shows a field based on yes and no and another drop down that shows a number of fields depending on a numbers (1,2,3,4,etc)?

    Thanks

    Andrew

  60. Have you written a script to create a slide show from an images library where you can control the order of the images? The default images library does not allow you to control the order of the images in the default slide show capability – it goes by creation date.

    1. Hi Ben,
      I have not done anything like this. Look at the links provided by Larry.

      You may place another request if you do not find what you are looking for, and i will look at it if i find time.

      Alexander

  61. I see you are busy and I just keep adding. I will help out on your questions as much as I can. I have a New request. In a grouped view, if grouped by a people picker SP displays their account name. Can this be switched or swaped with their display name?
    example by default:
    DomainFLast

    change to:
    First M Last

    1. Hi Larry,
      Thank you for helping out in answering questions – nice job yesterday.

      This has to do with the “information type” selected in the list settings for the people picker. You can change it there to “Name”.

      Alexander

    2. My problem is these Items are added by a workflow create new ilist item. The only way to ensure name to be written, I need the Account Name meaning I would continually need to switching them back an forth. Can we modify your script to access user profile and swap the account name with display name?

    1. This code strips off all leading and trailing whitespace (uses the regEx you supplied):

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      function PreSaveAction(){
      	var myField = $(fields['Title']).find('input');
      	var properVal = myField.val().replace(/^s*|s*$/g,'');
      	myField.val(properVal);
      
      // Must return true to save item
      return true;
      }
      
      
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Place in CEWP below NewForm or Edit Form (read here how to do that);

      Updated: Missed “return true” in the function PreSaveAction()

      Alexander

    2. I want to edit this to force numberical valuse on a singleline textfield. reason is I dont want commas.

      What is the expression?
      instead of val().replace
      if the expression != numbers
      alert(“”);
      else
      ok to save

      this should be fairly easy. I am going to search for the regex. and try to produce it. if you have any suggestions they are welcomed

    3. that actually replaces the value with blanks, no alerts. If I want to set length = 9; and alert the user to make the changes I would need to compare. I cannot figure that out.
      If not Num and not length = 9, alert user, no save

  62. On the choice menu there is an option to allow user to Specify own value. is there a way to replace the text “Specify your own value:” and hide the field until the radio button for this is selected?

    1. hiding the original DD may cause an issue. I think hiding the textbox until other is selected wold be a better functionality. remember specify other value is used for checkboves also.

  63. Hi Alexander:
    I need my users to click an “Add New” icon next to an item in a List View and have a NewForm pop-up with the same [Company Name] field already populated. Possible?

    As always, Thanks-

    Charlie Epes

    1. There are also a few script, think I have one for the NewForw to populate a field from query string. We can wolk thru this step by step if you need the help

    2. Hi Larry:
      I’m very familiar with Christophe’s html calc field but how can I work it into this scenario?

      I need to be able to grab a specific field from the first list.

      Charlie

    3. sorry here is a sample calc field you could use

      ="<DIV><a href='/pathto yournewform/NewForm.aspx?ClientVal="&[Client Field]&"'><img src='/pathtoyourimage/img.gif'></a></DIV>"
      
    4. Hi,
      If you use the method described by Larry, you can grab the querystring “ClientVal” from the url with parts of the script found here:
      SharePoint form: scroll to field as with an anchor tag

      Like this:

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      // Get all querystring parameters
      var queryStr= getQueryParameters();
      
      // Is the parameter "ClientVal" defined?
      if(queryStr['ClientVal']!=undefined){
      	var properVal = decodeURI(queryStr['ClientVal']);
      	$(fields['Title']).find('input').val(properVal);
      }
      
      // Function to separate each url search string parameters
      function getQueryParameters(){
      qObj = {};
      var urlSearch = window.location.search;
      	if(urlSearch.length>0){
      		var qpart = urlSearch.substring(1).split('&');
      		$.each(qpart,function(i,item){
      			var splitAgain = item.split('=');
      			qObj[splitAgain[0]] = splitAgain[1];
      		});
      	}
      return qObj;
      }
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      This code gets the parameter “ClientVal” from the queryString and inserts it in the “Title” field.

      Alexander

    5. Hi Alexander:
      Coach me a little on this. I have my html calc column all set up like Christophe had. Where do I insert your script? a cewp on the List view or on the new form?

      Charlie

    6. One more questions:

      My Title field is named “Company Name”. When I insert ClientVal=”&Company Name&”, I get “not support syntax.

      When I insert “ClientVal=”&Title&”, it says it refers to a column that does not exist.

      Do I have to insert the title field? Am I inserting the internalfieldname or the shown name?

      Thanks-

      Charlie Epes

    7. Hi Alexander:
      I think this solution is worthy of a blog post!

      Perhaps, “Open Duplicate-Title List Item in NewForm Window”.

      Anyway, you and Larry helped me immensely today-

      Charlie Epes

    8. Hi Alexander (and Larry):
      Small issue, but which ever image I use from the SP image gallery, the List View with the html column puts a heavy blue or mauve border around the image.

      I know the color shows if I have previously clicked it, but is there a way to get rid of the border so the image appears as clean as the Edit icon?

      Thanks-

      Charlie Epes

  64. Hi Alexander:
    Coach me a little on this. I have my html calc column all set up like Christophe had. Where do I insert your script? a cewp on the List view or on the new form?

    Charlie

    1. the script should be placed on the NewForm. this is where the query string is available, you will see in in the URL, Alexander’s script will grab it from there and write it to your field.

  65. Hi Alexander,

    this has been by far the most informative resource I’ve read today and combined with Christophe’s site it’s a valuable addition to my favourites list.

    I’m a sharepoint newbie but found myself somehow as one of two designing an internal site for our team. We thought about different opportunities to set up the site, though one thing was clear, we wanted to get rid of the typical explorer like folder structure and nesting.

    Our idea sounded simple and logical, however today we learned that it might not work at all.

    Instead of having multiple document libraries for different access levels we had the idea to incorporate a “visible to” column to define access by using metadata information.

    The plan was to have e.g. team1 and team2 have read/write access to a doc library and each of them would only see documents tagged with the relevant visibility level. Turns out that we can’t restrict the visibility based on access level since there is no obvious way to match metadata against a group/role.

    Since we only have site admin access our only help would be a cewp doing some sort of lookup of the user/group trying to access the doc library matching against the metadata column. The column can contain multiple values.

    Do you think that it might be possible to solve this with some javascript code and point us into the right direction?

    thanks
    Chris

    1. endusersharepoint.com had a neat script that allowed you to create folders with permissions based on views. Since they moved their site some of the items have not yyet been posted. I will try to find the original post. I think this can help you. Give me a day to find it.

    2. Hi Chris,
      I will write an article about this. I have had the same requirement myself, and have the scripts already made.

      The method i used involved reading the “team name” from the user profile (the WSS profile or the MOSS SSP profile). You can also read the team name from a cookie.

      I then take the team name and uses JavaScript to filter the view based on the value in the “Visible to”-column. This column must be visible in the view for filtering purposes, but the script can hide the column if desired.

      By using another of my scripts, you can filter the list based on group membership.

      This method have some limitations regarding grouped views. I will describe them in the coming article.

      One other method for filtering a view is by using the URL-filter. This method is very god as it does not require the column to be in the view.

      The disadvantage of the URL-filter is that the filter must be included in the link for it to be applied without refreshing the page.

      I cannot promise a delivery date, but will try to get it done by the middle of next week.

      Alexander

    3. Larry, Alexander,

      thanks a lot for picking up on this topic. On friday we tried a possible workaround using views but we weren’t able to restrict access to the other views nor the document library itself. WSS would always asign read to the document library if read was set to a specific view.

      I’ll have a look at the eusp link and I’m definitely looking forward to reading your article, Alexander.

      Again, thanks a lot for your help!

      Chris

    4. Larry,

      I’ve read the description on eusp, but I can not find the script? Is there a trick to it? There’s only the “…add in the following script:”

      And then an explanation on how the sript works, but no code?

      Chris

    5. Thanks Alexander, will try it in detail tomorrow. So far I had no luck in getting it to work, I’ve downloaded a copy of jquery 1.4.1, changed the path/version but nothing happened.

      Is there a chance that this will work in doc libraries, too?

      Chris

    6. Hi,

      haven’t been able to get this to work. I don’t even know if the jquery part works or not since I don’t know how to verify this. Is there something I can insert into the code that will give me an indication as to wether or not the script is actually called?

      Chris

  66. Hi Alexander!

    I have a multi-line text field I want to allow users to update in a datasheet view. The problem is that they can’t add multiple lines of text while in datasheet mode. Any ideas on how I can give them this ability?

    Thanks!
    Amy

    1. Hi,
      You can edit multiple lines of text in datasheet – not enhanced rich text, but both plain text and rich text are editable. Is it the linefeed (Enter key) that is the problem?

      If so, use Alt+Enter for linefeed – like in Excel.

      Alexander

    1. Like this:

      $(fields['RichText']).find('.ms-formbody').after("<td><div style='font-size:10px;color:red'>Add the HTML<br>code here</div></td>");
      

      Alexander

    1. Using Alexanders script here you go:

      <script type="text/javascript">
      
      fields = init_fields();
      
      $(fields['Title']).find(".ms-formlabel h3").hide(); // Hides the field Title
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7;
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      
    2. Usually I use this in combination with writing new labels.
      Here I replaced line 5 from above with this:

      var myLabel = "My New Label"
      $(fields['Title']).find(".ms-formlabel h3").hide().after(myLabel);
      
      
  67. Hi Alexander, I did not succeded wiht the code that strips off all leading and trailing whitespace (and use the return true), have for example a complete new custom list with only a default Title field, and have the link to the latest min right, and have the CEWP below. Some idea?

  68. hi Alexander,
    i accidently stumbled on your great blog search for a way to modify my lsitview with javascript.

    here’s what i would like to accomplish:
    i have this allitems view with multiple columns. One of these colums is of the multi lines of text.
    When i start editing my items my multiline column cell strats growing in size due to a point that i can only see one item in my screen and need to scroll down to see other items in the list.

    Is there a way to limit the number of characters in the multi line column (named “Voortgang en resultaat”) to show less characters: preferably one line of text or text up until some splitting character?

    thanks,
    ronajon

  69. Hi, thanks again for all nice posts here, always intresting stuff here!

    I try to figure out how to change the output text for the standard buttons in a newform.aspx, i want to change OK to Save for example. Have tried the ‘replaceWith’, but I don´t know how to get the text when it´s a value? Any ideas here?
    /C

  70. choice – Multiple select, check boxes, is there a way to have multiple default values. I may want the same 3 items to always be selected. by default SP only allows one option. This field for 90% may need those 3 requests. Can it be done?

  71. Hi Alexander & Larry:
    I was hoping that I could use borrow some advice & suggestions from both of you on the setup and output of a SharePoint List.

    I have Alexander’s email, but Larry I am wondering if I might email you too. My email is charlie dot epes at fnrm dot com.

    Thanks-

    Charlie Epes
    Buffalo, NY

  72. I know you had a post related to people picker fields and populating other people picker fields from an external list. I want to tweak this.
    3 single line text, first field (uses your script text to choice) to get value in external list, field2 and field3 auto populate. I just cant get this script converted. How can this script be changed to text fields, first field is text to choice. is is a quick change?

    <script type="text/javascript" src="/sites/learning/Scripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="/sites/learning/Scripts/interaction.js"></script>
    <script type="text/javascript" src="/sites/learning/Scripts/stringBuffer.js"></script>
    <script type="text/javascript" src="/sites/learning/Scripts/AccessUserProfileInWSS.js"></script>
    <script type="text/javascript" src="/sites/learning/Scripts/SetPeoplePicker.js"></script>
    
    
    <script type="text/javascript">
    fields = init_fields();
    // FieldInternalNames from manager list
    var arrOfFieldInternalNamesInManagerList = ['Manager','Manager2'];
    // FieldInternalNames from this list to write the data back to
    var arrOfFieldInternalNamesInThisList = ['Manager','Manager2'];
    // Hide all the people picker fields
    $.each(arrOfFieldInternalNamesInThisList,function(i,fin){
    	//$(fields[fin]).hide();
    });
    // Get managers for current user - "_spUserId" is current user
    var userAndManager = getManager('ManagerList','User',_spUserId,arrOfFieldInternalNamesInManagerList);
    
    // Wait until page has finished loading, then fill the manager fields
    $(document).ready(function(){
    	$.each(userAndManager,function(i,item){
    		var split = item.split(';#');
    		var userID = split[0];
    		var dispName = split[1];
    		var ui = getUserInfo(userID);
    		// Set the people pickers value on load
    		setPeoplePicker(arrOfFieldInternalNamesInThisList[i],ui.Name);
    	});
    });
    
    // Function to set the people picker value - slighly modifid to handle hidden fields
    function setPeoplePicker(FieldInternalName,loginName){
    var field = $(fields[FieldInternalName])
    	if(field.find('.ms-inputuserfield').css('display')!='none'){
    		// IE
    		field.find('.ms-inputuserfield').html(loginName);
    		field.find('img:first').click();
    	}else{
    		// FF
    		field.find("textarea:first").val(loginName);
    	}
    }
    
    // Custom function to pull managers from anoher list based upon current users ID
    function getManager(listNameOrGuid,FieldInternalName,userId,arrOfViewFields){
    	wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
    	var query = "<Where><Eq><FieldRef Name='" + FieldInternalName + "' LookupId='True'/><Value Type='User'>" + userId + "</Value></Eq></Where>";
    	var res = queryItems(listNameOrGuid,query,arrOfViewFields,1);
    		var item = res.items[0];
    		var ret = [];
    		$.each(arrOfViewFields,function(i,fin){
    			ret.push(item[fin]);
    		});
    		return ret;
    }
    
    
    function init_fields(){
    var res = {};
    $("td.ms-formbody").each(function(){
    if($(this).html().indexOf('FieldInternalName="')<0) return;
    var start = $(this).html().indexOf('FieldInternalName="')+19;
    var stopp = $(this).html().indexOf('FieldType="')-7;
    var nm = $(this).html().substring(start,stopp);
    res[nm] = this.parentNode;
    });
    return res;
    }
    </script>
    
  73. Hi Alexander:
    Further to your Multiple Choice Checkbox solution, do you know of a way to add a “Select All” to all checkboxes on an entire form?

    Thanks-

    Charlie Epes

    1. In your choice field (checkboxes) add a value “Select All”
      add CEWP with this script

      <script type="text/javascript" src="/sites/learning/Scripts/jquery-1.3.2.min.js"></script> 
      <script type="text/javascript">
      _spBodyOnLoadFunctionNames.push("initJQuery");   
      
      function initJQuery(){
        $(document).ready(function(){   
      
          $(".ms-RadioText[title='Select All'] :checkbox").css({border:"2px green solid"});   
      
          $(".ms-RadioText[title='Select All'] :checkbox").click(
             function(){
                       var otherids = (this.id).substring(0, (this.id).length-2 );
                       $("input[id^='"+otherids+"']").attr( "checked" , (this.checked)?"checked":"" );
      
             });   
        });
      }
      </script>
      
    2. just update to reference to jquery. I have been able to run this with the code above and below the NewForm, EditForm. This probably could be tweaked a little cleaner, but it works very smooth.

      If anyone is interested, when dealing with Forms library there is a repair or relink action. again depending on the amount of documents could be many boxes to check. I have adapted a script to add a select all on that page also.

    1. Hi,
      I will take a look at this when i find the time. I think it would be possible either by writing the rating to the item itself, or by writing to another list.

      I unfortunately have little time to spare, so i cannot promise anything, but i have added this to the queue.

      Alexander

  74. Hi there hope you can help!

    I need to get working – highlighting a row in SharePoint when the mouse hovers over it and when clicked on, selects the row entry displaying the dispform.aspx page.

    I have achieved this through Sharepoint Designer but really need it to work on a normal SharePoint list.

    Christophe got the highlight to work I noticed but I really need the dispform.aspx page displayed when clicked on anywhere along the row.

    Again – hope you can help!

  75. I am trying to disable OK button if choice equals “No” and enable if Choice equals “Yes” (not Yes/no choice, Radiobutton choice). here is the code I have. I took it from part of your dynamic hide show multiple select. Can you tell what I am missing?

    <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
    // Multiselect  
     $(fields['A']).find('input').each(function(i){  
        // On page load  
        if(i==0){ // call this only once  
            MultiSelectdynamicDisplay($(this));  
        }  
        // Add onclick  
         $(this).click(function(){  
           MultiSelectdynamicDisplay($(this));  
        });  
    
     });  
        
     function MultiSelectdynamicDisplay(inp){  
     var objChecked = {};  
     var inpAll = inp.parents('td.ms-formbody:first').find('input');  
         $.each(inpAll,function(){  
             objChecked[$(this).next().text()] = $(this).attr('checked');  
         });  
         // Check each option  
         if(objChecked['Yes']){  
             $("input[id$='SaveItem']").attr('disabled',false);  
         }else if(!objChecked['No']){  
             $("input[id$='SaveItem']").attr('disabled',true);  
         }  
    
    
     }  
    
    </script>
    
    1. Disable Choice option until Yes is selected:
      Here you go:

      <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      // Multiselect  
       $(fields['A']).find('input').each(function(i){  
          // On page load  
          if(i==0){ // call this only once  
              MultiSelectdynamicDisplay($(this));  
          }  
          // Add onclick  
           $(this).click(function(){  
             MultiSelectdynamicDisplay($(this));  
          });  
      
       });  
          
       function MultiSelectdynamicDisplay(inp){  
       var objChecked = {};  
       var inpAll = inp.parents('td.ms-formbody:first').find('input');  
           $.each(inpAll,function(){  
               objChecked[$(this).next().text()] = $(this).attr('checked');  
           });  
           // Check each option  
           if(objChecked['Yes']){  
               $("input[id$='SaveItem']").attr('disabled',true);  
           }else if (!objChecked['Yes']){ 
      $("input[id$='SaveItem']").attr('disabled',false);
       }
           if(objChecked['No']){  
               $("input[id$='SaveItem']").attr('disabled',true);  
           }else if (!objChecked['No']){ 
      $("input[id$='SaveItem']").attr('disabled',false);  
       }  
      
      
       }  
      </script>
      
    2. forgot the most important part

      // add before line 3 above
      fields = init_fields();
      
      // add after line 34 above
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      
    1. <script src="http://www.google.com/jsapi"></script>
      <script>
      google.load("jquery", "1.3.2");
      google.setOnLoadCallback(function() {
      $(document).ready(function()
      {
      // jquery 1.2.6
      //jQuery.extend(jQuery.expr[':'], {
      //containsIgnoreCase: "(a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0"
      //});
      jQuery.extend(jQuery.expr[':'], {
         containsIgnoreCase: function(a,i,m) {return (a.textContent||a.innerText||jQuery(a).text()||'').toLowerCase().indexOf((m[3]||'').toLowerCase())>=0}
      });
      
      $("table.ms-listviewtable tr.ms-viewheadertr").each(function()
      {
      if($("td.ms-vh-group", this).size() > 0)
      {
      return;
      }
      
      var tdset = "";
      
      var colIndex = 0;
      
      $(this).children("th,td").each(function()
      {
      if($(this).hasClass("ms-vh-icon"))
      {
      // attachment
      tdset += "<td></td>";
      }
      else
      {
      // filterable
      tdset += "<td><input type='text' class='vossers-filterfield' filtercolindex='" + colIndex + "' /></td>";
      }
      
      colIndex++;
      });
      
      var tr = "<tr class='vossers-filterrow'>" + tdset + "</tr>";
      
      $(tr).insertAfter(this);
      }); 
      
      $("input.vossers-filterfield")
      .css("border", "1px solid #7f9db9")
      .css("width", "100%")
      .css("margin", "2px")
      .css("padding", "2px")
      .keyup(function()
      {
      var inputClosure = this;
      
      if(window.VossersFilterTimeoutHandle)
      {
      clearTimeout(window.VossersFilterTimeoutHandle);
      }
      
      window.VossersFilterTimeoutHandle = setTimeout(function()
      {
      var filterValues = new Array();
      
      $("input.vossers-filterfield", $(inputClosure).parents("tr:first")).each(function()
      {
      if($(this).val() != "")
      {
      filterValues[$(this).attr("filtercolindex")] = $(this).val();
      }
      }); 
      
      $(inputClosure).parents("tr.vossers-filterrow").nextAll("tr").each(function()
      {
      var mismatch = false;
      
      $(this).children("td").each(function(colIndex)
      {
      if(mismatch) return;
      
      if(filterValues[colIndex])
      {
      var val = filterValues[colIndex];
      
      // replace double quote character with 2 instances of itself
      val = val.replace(/"/g, String.fromCharCode(34) + String.fromCharCode(34)); 
      
      if($(this).is(":not(:containsIgnoreCase('" + val + "'))"))
      {
      mismatch = true;
      }
      }
      });
      
      if(mismatch)
      {
      $(this).hide();
      }
      else
      {
      $(this).show();
      }
      }); 
      
      }, 250);
      });
      });
      
      });
      
      </script>
      
  76. Hi there! I need a script or any solution in SharePoint to just display a note/comments. Is there perhaps a script that can hide the response field on a form so I could just display the column title with the note/comments?

  77. Hi Alexander! Another challenge for you, i´m searching a way to make a document library automatically name the new folders created sequentially, i mean, the first folder´s name would be 001, the second one 002,… Do you think that could be solve using script?

    I hope you can help me! thank you very much! 🙂

  78. I have list view. On above I want to give 3 control i.e. StartDate (Datefield), Enddate(Datefield), Checkboxes (Choice field) and a button i.e. “Search”. I tried with SPD, but not happy.

    First I want to validate that Start date shounot be >= Enddate after selection, user will select checkbox value (can be more then 1)

    Then user will click on Search button thne records will filter depending on selected criteria and display in view.

    Please advise

    1. A far as i know you cannot filter a standard SharePoint list view based on on a date range. At the moment i cannot provide you with any solution, sorry.

      Alexander

  79. I have 1 transaction List which has various fields, out of them 2 fields i.e. Name and Type (choice field) I want to generate a cross tab report. Where Name display vertically and type display horizontally.

    Please help me out, I am not sure how to do it

    Name1 Choice1 – Choice 3 Choice 4 –
    Name2 – – – Choice 4 –
    Name3 – Choice2 Choice 3 – Choice 5
    Name4 Choice1 – Choice 3 – Choice 5

    1. can you provide a screen shot of what you are trying to achieve. I believe I think I understand. Looking at what the text displays its a bit difficult. is Choice1, Choice2.. fields or options of a field? I believe this could ne accomplished with a calculated field.

    2. Lary

      Choice1, Choice2, Choice3.. fields are a values of a “Work Type” field, its field type is ‘Choice’ it is displaying as Checkboxes with multiple selections.

      If we discuss about functional logic i.e. Which Contact(Name field) is eligible for which work type, which we have normally set during new record creation.

      Let me know if you need more information.

    3. I spent a good poprtion of the day trying to work this out. I came very close. the problem I was having is with the multiple select. I am having problems reaading part of the string. If it was only for single select we would be done. With the use of calculated fields, HTML and Christophes script HTMLcc we could create a proof of concept. I will contine to tinker. Maybe Alexander will come up with something.

    4. Okay I have finally achieved proof of concept. I started out with the two fields you had
      – Name
      – WorkType
      Set WorkType to single line field
      Created a calculated field “calc”
      set it equal to WorkType.
      Now WorkType must be deleted, then recreated as your choice, multiple select field. this is the only way calc returns the values in WorkType as a string. calc wont read WorkType unless you trick SharePoint.
      The next set of fields depends on the number of options you have. I did it with 5 options so i created 5 calculated fields
      opt1 =IF(FIND(“Choice 1″,calc),”Choice 1″,””)
      opt2 =IF(FIND(“Choice 2″,calc),”Choice 2″,””)
      opt3 =IF(FIND(“Choice 3″,calc),”Choice 3″,””)
      opt4 =IF(FIND(“Choice 4″,calc),”Choice 4″,””)
      opt5 =IF(FIND(“Choice 5″,calc),”Choice 5″,””)

      The formulas are searching the string for that value. When you setup yours Choice 1 would be your option 1, same thing for the returned value if true.

      As it is it returns the values in each column as iut should , but the find formula returns #VALUE! it the formual is false. I looked at a script and placed it on the page to do a string replace.

      In a CEWP under the list view add this script

      <script type="text/javascript">
      var theTDs = document.getElementsByTagName("TD");
      var i=0;
      var TDContent = " ";
      while (i < theTDs.length)
      {
        try
        {
          TDContent = theTDs[i].innerText || theTDs[i].textContent;
          if (TDContent.indexOf("#VALUE!") == 0)
          {
            theTDs[i].innerHTML = TDContent.replace(/#VALUE!/,"").replace(/#VALUE!/g,"");
          }
        }
        catch(err){}
        i=i+1;
      }
      </script>
      

      it is not jquery, but if someone wants to convert it I would be okay.

      let me know if you have any questions

    5. Larry

      Thanks for this. I appreciate this and agree that without calculated fields it is not possible. That means need to create 5 calculaeded fields thne why do I need implement yout script.

      I can create simple view with following fields Iwith yes/no option) and it will display horizontally.
      Name
      Option 1
      Option 2
      Option 3
      Option 4
      Option 5

      What do you think?

    6. Hi Avi,
      Is the result Larry presented what you want?

      To take the selected options from a multi choice and insert them in separate columns. You would then have one “Plain text field” for every available option in the multi choice?

      What is the end result you want? – to filter and sort by the values?

      It is a bit unclear to me actually what you want to achieve – that you do not already have in a standard list view.

      If you provide an illustration of what end result you imagine, i might be able to help.

      Alexander

    7. Avi,

      You right about why not just create 5 yes/no fields. Thats not what you asked for. So I worked this a little more and the solution I came up with works with 2 calculated fields now and your options are in a table format.

      I was able to figure out the calc formula that did not return the #VALUE! on error.

      you still need to start out the same way. set WorkType to Single line text.
      Create field “calc” = [WorkType]
      change WorkType back to choice multiple select
      Create a calc field with this formula

      ="<DIV><table style='width: 100%;' Class='ms-vb2'><tr>
      <td style='width: 25%'>"&IF(Name<>"",Name,"")&"</td>
      <td style='width: 15%'>"&IF(NOT(ISERROR(FIND("Choice 1",calc))),"Choice 1","")&"</td>
      <td style='width: 15%'>"&IF(NOT(ISERROR(FIND("Choice 2",calc))),"Choice 2","")&"</td>
      <td style='width: 15%'>"&IF(NOT(ISERROR(FIND("Choice 3",calc))),"Choice 3","")&"</td>
      <td style='width: 15%'>"&IF(NOT(ISERROR(FIND("Choice 4",calc))),"Choice 4","")&"</td>
      <td style='width: 15%'>"&IF(NOT(ISERROR(FIND("Choice 5",calc))),"Choice 5","")&"</td></tr>
      </table></DIV>"
      

      for this code to work and display a table you will need the script text to HTML from christopthe site here:
      http://www.pathtosharepoint.com/HTMLcc/default.aspx

    8. Lary

      Thanks, this is what I am looking for.

      How can I used in new custom page? I have added CEWP, but how do I pass the list reference with this code?

      Again thanks a lot.

      Avi

    9. passing the list reference is different then populating a calculated field. if you create this function in a list, then anywhere you display this list, the calc fields will also populate. this layout is for the output on your list views, or the dispform.aspx page, to convert the HTML to display, this will be placed into a CEWP below the list or below the list form. follow the link for the scipt and there are instructions on how implement

  80. Hello

    I have tasks list where we are assigning task to different staff persons on different dates. For assigning we are not using using people / group field type, we are using a calculated text field (First Name + ” ” + Last Name).

    I want to display weekly calendar with next/previous navigation and schedule of each staff link as shown below

    Initially it will display the weekly calendar with staff name under each
    day column, but once user click any staff link name from the left menu weekly calendar then selected staff task will display in the weekly calendar

    Is this possible?
    ——————————————————————-
    Staff | Week of <<>
    | Mon Tue Wed Thu Fri
    | —– —- —– —- —
    … | —– —- —– —- —
    | —– —- —– —- —
    | —– —- —– —- —

    1. Calendar Look Like
      ————————————————–
      Next Week Previous
      ————————————————–
      Staff Mon Tue Wed Thu Fri
      Staff1 — — — — —
      Staff2 — — — — —
      Staff3 — — — — —

    2. Sorry, but i do not think i can help you with this one at the moment. I have done very little modifications on a calendar view.

      Alexander

  81. Hi Alexander:
    One of my wishes is to be able to print Lists to paper and be able to set the column names and perhaps the banner of a List view as repeating page headers on the printout.

    I imagine that JQuery cannot control a printout but perhaps it can divide a list view into selectable lengths with the column names so the printing it would mimic an Excel prinout with headers.

    Footers on each page would be great too!

    Charlie Epes

    1. I’m not quite sure where you want this menu, and what is it supposed to contain? – static elements or dynamic elements?

      Alexander

  82. Hi Alex thank you for all your great work, you showed me how to add a help link after a rich text box, is there away to add it right after its title/name? For example filed name is description and have it appear like:

    Description (Click here for help) and then the field…….

    Tony

    1. https://spjsblog.com/2009/10/29/add-html-mouseover-tooltip/

      He also had a simple title tool tip, I am sure the text could be converted. or can try this

      <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      var myHTML = "<div><a href='#'>text</a></div>"
      
      $(fields['Title']).find("td.ms-formlabel h3").after(myHTML);
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      
      

      this is Alexander,s script

  83. Hi,
    Wondering if anyone has figured out a way to create a cascading dropdown where the child dropdown is a Person/Group type field… e.g. Team and Team Member.

    Any guidance is appreciated.

    Travis

    1. Hi Alexander,
      Yes, that was my thought… to have a separate list as most cascading lookups I’ve seen implemented… so:

      Cascade Reference List Columns:
      Team Name (Text, Dropdown, or Lookup column type)
      Team Member (Person column type)

      Make sense? Any idea how to accomplish something like this?

      Thanks,
      Travis

    2. The cascading dropdowns script i have made can have a person (from a people picker field) on the last dropdown.

      This script relays on single line text fields rendered as dropdowns, and cannot insert the “picked person” in a “picker field”.

      Alexander

  84. Hi Alexander:
    Similar to your “Today Date Picker Clicker”, I am wondering if you know of a way to click yes/no in a list view.

    I have a list with 31 choice fields with options of Yes and No (NOT a Yes/No check box). I would like a user to be able to click yes or no on the list view “cell” beneath the field. Clicking once would mean Yes, clicking again would leave it blank or No.

    I know your today date picker was placed on a newform/editform. Is this possible on a list view?

    Thanks-

    Charlie Epes

    1. Scratch that… I would be happy with the Yes/No check box field type being clickable on the list view, so it’s either on or off.

      Thanks-

  85. Howdy,
    How would I go about a simple tool tip for a ordinary list. I can only use Java Script within a CEWP. I am trying to notify the user that when then hover over any item of the list that “Click to Filter”…I am using connected lists that filter and provide data to each other.

    1. do you want a tool tip for a single cellin a row, or for the whole row?
      For a single cell this can be done with a calculated field and a hyper link like this.
      [sourcecode]
      ="<DIV><a href=’#’><img src=’help.gif’ title=’tool tip here’></a></DIV>"

      to make this work your need a script from Christophe at pathtosharepoint.com here:
      http://www.pathtosharepoint.com/HTMLcc/default.aspx

      If you a more dynamic tooltip, I found this one to be pretty good and can be implemented into the calc field formula above
      http://www.walterzorn.com/tooltip/tooltip_e.htm

    2. Hi,
      To add a plain text mouse over tooltip to the entire row, add this code to a CEWP below the webpart. You will have to identify the id of the WP you want to add this tooltip to, and replace “WebPartWPQ3” in the code.

      Use IE Dev Toolbar, or FireBug for FireFox to inspect the code.

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      $("div[id='WebPartWPQ3'] tr").each(function(){
      	$(this).attr('title','Click radio button to filter connected list...');
      });
      </script>
      

      Alexander

  86. Hi Alexander:
    Another “is it possible?” question…

    Is it possible to have a specific column’s filter choice appear in a CEWP that I would place above a list view?

    Example: Filter the page by [Customer]
    CWEP: would contain text + [Customer]

    Thanks-

    Charlie Epes

  87. I also have same type of question but slight different.

    I want to filter my list by 3 inputs i.e. Start Date/End Date and Checkbox field.

    I will ask user to select start date/end date (with validation of start date should not >= end date) and a 3 checkbox (leavetype) i.e. casual, holiday, medical and a go button

    In the list I have requesdate and a choice field of leavetype (which allows user to select multiple value)

    Now once user enter start date, end date and select 1 or multiple chackbox, my list should populate.

    Is this possible?

    1. Hi,
      This one answered in another comment above, and i have to disappoint you:

      A far as i know you cannot filter a standard SharePoint list view based on on a date range. At the moment i cannot provide you with any solution, sorry.

      Alexander

  88. Howdy!

    Hi Alexander, how are you doing? I haven’t seen any posts related to this, but please correct me if I’m wrong…
    Is there a way to change the background color of specific fields in a list view using jQuery? I’ll give you a sight of what I need:
    There is a table with the weeks of each month… side by side.. and the users must select a range of weeks that they’ll use for vacation. The fact is, my manager asked me to have the filled fields with a background color (blue for approved vacations and red for rejected ones). I hope I could get you the Idea. Well, thank you very much for the attention =)

    Victor

  89. Hello

    I have two choice fields, 1 drop down and another is multiple radio buttons (6 values/radio button). This I want to implement on newform/editform

    In dropdown I have 3 values i.e. Yes/No/Not Sure (selected by default).

    I want to show/hide some of the radio buttons out of 6 radio buttons depending on condiion.

    Let say
    if user select “Yes”, then show radiobutton1 and radiobutton 3
    If user select “No” , then show radiobutton2 and radiobutton 5
    If user select “Not Sure” thne show all the radio buttons

    How can I do this?

  90. new request for you. Character/word counter for multiple line field to display below the field. Not general for all multiple lines, but setup in a way that can set fieldinternalnames in am arr. also can we add a character limit, so user can not enterany more text.

    I have several character counters. cant get it on the form. I am also looking into adding it on the create field page. calculated fields can only accept about 1000 characters. would like a way to display the count on that page.

  91. Hi Alexander

    I have a drop down field in a sharepoint list which is populated with long selections. When the NewForm and EditForms are viewed on screen they require scrolling right to view them. Is there a way on the form of showing a number of characters with the … after?

    Thanks

    Andrew

    1. Add this code to a CEWP below the NewForm or EditForm. The FieldInternalName of the select in the example is “MySelect”, you must change this to match your field.

      On mouse-over on the truncated text, you get the full text.

      <script type="text/javascript" src="../../Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      $(fields['MySelect']).find('option').each(function(){
      	var thisText = $(this).text();
      	var newText = thisText.substring(0,60)+"...";
      	$(this).text(newText).attr('title',thisText);
      
      });
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return; 
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7; 
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Alexander

  92. In a Custom Workflow users edit their Tasks associated with this workflow.

    In these Tasks there is an option for them to enter a comment in a Comments field.

    Is there a way to show this Comments field on the WrkStat.aspx page?

    Also, is there a way to highlight the Outcome field if it is set to Approved or Rejected?
    e.g. green if approved or red if rejected.

    1. Hi,
      A modification on this page must be done on the server. This page is shared between all web applications running on the server. I cannot help you with this one, sorry.

      Alexander

    2. eru, I’ve played with this before, and you can build a dynamic string (comments) and write it to the workflow history log. You may have to play with formatting.

  93. I know this topic has come up before and I have pointed users toward other posts. Hos to do with filtering a list. there is a pretty good script out there that applies text boxes to each column and it filter on entered text. Today I was looking in to changing the textfields into dropdowns. Then i came across this webpart that creates a form at the top of the list and it has a date span filter. very kool. Even if the date span can be achieved thru jquery. is there a way to create a form that pulls data from multiple columns in a list and then can filter on select? What I think is a key featuer is the multiple select filter and right above the list.
    http://www.kwizcom.com/ProductPage.asp?ProductID=404

    1. It is possible to do some of this with javascript, but I’m kind of overloaded and cannot help right now. I may come back to this.

      Alexander

  94. Yes back with list filters requests. Is there a way that a user can hide columns of choice? Just like the script in my last request post that displays text fields maybe display check boxes. When the box is selected the column is hidden leaving only the checkbox. Unchecking shows the column.

    With the above list filter script I found when user filters you can’t export that filtered view. The export exports all the data. Is there a way to have the dynamics filter and it retains the filert view on export?

    1. Hiding columns is possible, but as i stated above, I do not have the time to do it right now. I might come back to it later on.

      The export issue is not possible to overcome i think.

      Alexander

    2. I am sure you are busy. No worries I know if you have the time you’ll knock it out. I have been slammed myself, please don’t give it a second thought.
      thanks for all your efforts

  95. Awesome Blog! I’ve never seen such a collection of useful enhancements!

    I am having trouble converting my Excel powerusers to Sharepoint due to certain limitations. I hope you find some of these interesting:

    List View Issues:
    * Freeze Panes – ability to freeze the first column and/or the top row in a List View (I’ve seen solutions for top row, but not first column, or both)
    * Column Heading Tooltips – something like adding “comments” to cells in Excel. Could come from the field Description? Would display onmouseover.
    * Count/Sum/Average Calculated Columns – I’ve seen a solution for one column, but not multiple
    * Draw Column Lines – draw a line on the left or right edge of a column to have visual separation between blocks of columns
    * Color Column Headings – color column headings to provide visual separation / grouping of columns
    * Third Level Grouping / Sorting – (or more)

    New/Disp Form Issues:
    * Field Coloring – color field labels to provide visual separation / grouping of fields (in conjuction with above Color Column Headings)
    * Horizontal Separators – a line or other visual way to separate / group blocks of fields

  96. Sorry, I hope its not greedy to post multiple requests. This one is not related to Excel deficiencies.

    I need the ability to generate an html email, formatted just like the ootb alert email, by clicking a link or button contained in a List item column. The email would open in my email client (like Outlook). The TO: field would be empty but the Subject would contain the text of the List Item Title column. Here is the use case:

    I have a List that contains change request items. I need to “forward” a single item to a resource on my team and include comments like “hey, why is this taking so long”, or “please log in and approve this request”. I want the email I send to appear like the structured alert emails that Sharepoint already sends so that its very familiar to the user, has all the same “View Item” and “View List” links at the top, etc.

  97. So sorry. I forgot one key Excel feature that is missing in Sharepoint Lists. My users need the ability to do Excel functions similar to MATCH or VLOOKUP in Sharepoint. So the (somewhat confusing) use case would be:

    List1 contains change request items. List2 contains release information including the Deployment Date. In List1 I have a Lookup to the Release Number field in List2. I need to be able to select the Release Number in the Lookup field drop down, but retrieve the Deployment Date instead for inclusion in List1.

    The catch is that this association needs to be dynamic. So if I change the Deployment Date in List2, it changes in List1 as well (like Excel).

    1. This is actually what I’m working on right now. It will hopefully be posted this week.

      In your example it would be possible to make a calculated column in “List2” with a code like this:

      =[Release Number]&" ("&[Deployment Date]&")"
      

      And use this field as source for the Lookup in “List1”.

      Alexander

    1. Hi
      This code handles all external links in “ms-bodyareacell”:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      $("td.ms-bodyareacell a").each(function(){
        var title = $(this).attr('title');
        // Only external links are modified
        if($(this).attr('href').match(location.hostname)==null){
          $(this).attr({'title':title+' - opens in new window','target':'_blank'});
        }
      });
      </script>
      

      Alexander

    2. Hi Alexander:
      Thanks for the code. I can’t seem to get it to work. I’m replacing my JQ url, and I’m placing this inside a CEWP at the bottom of the page. What might I be doing wrong?

      Charlie Epes

  98. Yea, I have a big page of links and I would love to have it automatically open in a new window instead of asking/pushing the user/admin of the site to add the code each time.

    Thanks-

    1. then you can try this, but will still requre it to ne inplemented on each page.

      Get your weppart ID and update it below

      $('#WebPartWPQ1 a').attr('target', function() {
      //another way to limit by URL  within the CEWP  
       //if ($(this).attr('href') == 'mypage.com')
              //return '_self';
          return '_blank';
      });
      
  99. I have a button and a textArea field on a SharePoint page. When I click the button I want it to insert Today’s date into the textArea field. (NOTE: the name/ID of the textArea field could be anything because the user will add this to a SharePoint list).

    I have made the button appear on the Enhanced Rich Text Editor toolbar that appears on comments fields that are of type ERTE – Enhance Rich Text.

    I know how to generate the date but I am having trouble identifying the field on the SharePoint page so that I can set the value of it to the date. I also know how to identify the textArea field if the name is constant but when it is added by the user the field name is random.

    Do you know how to do this?

    1. Thanks for replying Larry. The function init_fields in the script fails at the “ms-formbody”. I put the function into my .js file that is loaded by the master page of the SharePoint site. Other .js functions in this work fine so I think it is loading correctly. But when I call this line: if (typeof (fields) == ‘undefined’) fields = init_fields(); it fails in the init_fields() function.

      function init_fields() {
      var res = {};
      $(“td.ms-formbody”).each(function() {
      if ($(this).html().indexOf(‘FieldInternalName=”‘) < 0) return;
      var start = $(this).html().indexOf('FieldInternalName="') + 19;
      var stopp = $(this).html().indexOf('FieldType="') – 7;
      var nm = $(this).html().substring(start, stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }

  100. Is there am easy way to hide some items in the View menu. The problem I am have is every one feels they need a specific view, So i can create a webpart part the displays these in tabs. In the mean time I have a list of views a mile long, not very user friendly. Maybe even hide the view selector until I can figure a better way to navigate the important views

  101. How can I prevent a dropdown box with more than 20 items from becoming a “filtered” drop down box? Right now my users have to double click a selection for my code to fire (which unhides/hides fields based on the selection)

    A lot of users are not double clicking, thus fields are not getting filled out because they are not viewable.

  102. Is it possibly to dynamically make a field required? If I’ve got a field hidden and I unhide it based on a selection, is it possible to at that point then make it required so they have to fill it out and prevent them from saving until it has some type of value?

  103. Using WSS 3.0

    Not have been able to find it anywhere so, since it is possible to filter a list items (in all event/task/etc view) based on membership in SharePoint group (By Alexander). I would like to request the possibility to filter an Agenda View on a single line text, based on a field of the current user information field (for instance department). I import data into SharePoint list what contains names of people. So users do not create the list items and there are multiple columns with names like Judge1 Judge2 Lawyer etc. As you all know you can’t use [ME] value in a single line text. This can only be used with columns: Created by, Modified by, Assigned to and People picking data. Problem with agenda view is also that it only displays 1 field (in general description of appointment for instance).

    What do I want?
    Filter (a) specific column(s) on the basis of the current user that is logged on (department field for example) in an agenda view.

    The agenda should only show items that match the same text as entered in the department field of the user information field of the user that is currently logged on.

    In my case IF Judge1 = Mr. J. Jenkins display it OR IF Judge2 = Mr. J. Jenkins display it. The OR statement is very important since SharePoint also filters with AND statement. So I would like to filter multiple columns with department field (any other also ok, as long I can fill in a value that is connected to the current user).

    I already managed to create something that filters all event/tasks/etc list view, searching all the columns based upon the current user department field with or statement idea, but not specific columns. Also in agenda view my code and Alexanders code will not work.

    If it is not possible to do this on each specific column it is also ok to search all of the columns since the names in my list are unique for each column. Other columns do not contain their names in such a way anyway. I’m already using my script for the not agenda view and works perfectly except user with slow internet will see the entire list my filter starts working.

    Excuse me for long text, but it is complex. Much appreciated any help, suggestion or solution.

    1. Hi,
      It will be both CAML and javascript. I have thought of querying the list with CAML to get an array of the ID’s to display. Then loop trough all “items” in the current view, and remove all not in the array.

      I’m afraid you will have to wait a bit before i come up with a solution, there are quite a backlog on articles to write.

      Alexander

    2. Thanks for the quick response again. Just asked so perhaps I can look in a certain direction en try some stuff. It is what I aspected the direction.

      If I figure something out I will let you know ofcourse,

      Thanks again.

    3. Just to keep you posted I tried all weekend including today lots of things, but to no prevail. I do know a calendar view for list view won’t accept connections however this was not possible to do anyway in wss 3.0. It is also very clear I cant just adjust aspx page to my liking with javascript or caml query sadly enough.

      From now on I will be patiently waiting, it gets to technical if I go any deeper I’m afraid. Finding and especially filtering the calendar items seems the hardest.

      This thing is a headache, hope I don’t transfer my headache to you.

    4. Hi Alexander,

      Tried filtering with SP designer with no luck. Can’t seem to accept it seems impossible. Perhaps you made any progress on the calendar filter?

      Thx again.

  104. Hi Alexander:
    I am looking for a way to insert code into a CEWP so that my current filter choice in my List View appears as text.

    Example:
    This report was prepared for: Alexander Bautz

    (where “Alexander Bautz” is filter I selected on the [Customer] field.

    Thanks-

    1. … I think the stress of moving my elderly parents has taken its toll on my memory. Sorry Alexander.

      Is there a way though to have the filter tag so I can place it into a CEWP and manipulate it?

      Thanks-

  105. Hi Alex

    I have two list that are connected through a web connection and I would like to hide a column on one of the lists. As you can see it is a regular aspx form not disp/edit/new.

    Can it be done?

    Tony

    1. Hi,
      Yes it can, i have made a note of this request, but cannot promise anything as i have quite a backlog on requests. You find some to work on in this post vLookup type rollup for SharePoint Look at the hiding of the ID column in the code (a snippet here):

      $(".ms-viewheadertr th").each(function(){
      	if($(this).find('table:first').attr('name')=='ID'){
      		IDcolIndex = $(this).attr('cellIndex');
      		// Hide ID column
      		if(hideId){
      			$(this).addClass('dummyHideClass');
      		}
      	}
      });
      
      $(".dummyHideClass").hide();
      

      Alexander

  106. Is there a way to dynamically change the description of a field? currently I am using ur script to change title of a field basedon content type. Would like to used the same functionality, just can’t figure to line of code to hide and replace existing description.

    1. It’s kind of difficult to get the description from a field, as it is not wrapped in its “own” tag. If you have plans on changing it dynamically, i would recommend you to handle it all in the script. use something like this:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      $(fields['yourFieldInternalname']).find('.ms-formbody').append("<div id='MyCustomDescription'>Your description here</div>");
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      Alexander

  107. I have another request hoping you can help me finish. It is along the 5 star rating request for items in sharepoint. Currently I have a calculated field, using Christophe’s text2HTML script, like this:

    ="<ul class='rating nostar'>
    <li class='one'><a href='#' onclick='alert("""&"1"&""")' title="""&"1 Star"&""">1</a></li>
    <li class='two'><a href='#' onclick='alert("""&"2"&""")' title="""&"2 Stars"&""">2</a></li>
    <li class='three'><a href='#' onclick='alert("""&"3"&""")' title="""&"3 Stars"&""">3</a></li>
    <li class='four'><a href='#' onclick='alert("""&"4"&""")' title="""&"4 Stars"&""">4</a></li>
    <li class='five'><a href='#' onclick='alert("""&"5"&""")' title="""&"5 Stars"&""">5</a></li></ul>"
    

    Here are my styles

    <style type="text/css">
    /* star rating code */
    /* all the stars are contained in one image to solve rollover delay */
    /* background position is shifted to reveal the correct image. */
    /* images are 16px x 16px */
    /* background position is shifted in negative 16px increments */
    /*  key:  B=Blank : O=Orange : G = Green * /
    /* Background-color position */
    /* B B B B B - (0 0)*/
    /* G B B B B - (0 -16px)*/
    /* G G B B B - (0 -32px)*/
    /* G G G B B - (0 -48px)*/
    /* G G G G B - (0 -64px)*/
    /* G G G G G - (0 -80px)*/
    /* O B B B B - (0 -96px)*/
    /* O O B B B - (0 -112px)*/
    /* O O O B B - (0 -128px)*/
    /* O O O O B - (0 -144px)*/
    /* O O O O O - (0 -160px)*/
    
    
    /* the default rating is placed as a background image in the ul */
    /* use background position from the table above for display */
    .rating{
    	width:80px;
    	height:16px;
    	margin:0 0 20px 0;
    	padding:0;
    	list-style:none;
    	clear:both;
    	position:relative;
    	background: url(/sites/globalmp/SiteImages/stars.gif) no-repeat 0 0;
    }
    /* ul classes shows the correct number of stars */
    .nostar {background-position:0 0;}
    .onestar {background-position:0 -16px;}
    .twostar {background-position:0 -32px;}
    .threestar {background-position:0 -48px;}
    .fourstar {background-position:0 -64px;}
    .fivestar {background-position:0 -80px;}
    ul.rating li {
    	cursor: pointer;
     /*ie5 mac doesn't like it if the list is floated*/
    	float:left;
    	/* end hide*/
    	text-indent:-999em;
    }
    ul.rating li a {
    	position:absolute;
    	left:0;
    	top:0;
    	width:16px;
    	height:16px;
    	text-decoration:none;
    	z-index: 200;
    }
    ul.rating li.one a {left:0}
    ul.rating li.two a {left:16px;}
    ul.rating li.three a {left:32px;}
    ul.rating li.four a {left:48px;}
    ul.rating li.five a {left:64px;}
    ul.rating li a:hover {
    	z-index:2;
    	width:80px;
    	height:16px;
    	overflow:hidden;
    	left:0;	
    	background: url(/sites/globalmp/SiteImages/stars.gif) no-repeat 0 0;
    }
    ul.rating li.one a:hover {background-position:0 -96px;}
    ul.rating li.two a:hover {background-position:0 -112px;}
    ul.rating li.three a:hover {background-position:0 -128px}
    ul.rating li.four a:hover {background-position:0 -144px}
    ul.rating li.five a:hover {background-position:0 -160px}
    /* end rating code */
    h3{margin:0 0 2px 0;font-size:110%}
    </style>
    

    with this image
    http://home.comcast.net/~larry.h.pfaff/stars.gif

    I have an alert in the onclick event and this all works. What i cant get or not sure how to do it how to track and average clicks. this set up uses classes to change the stars. It defaults to the class nostar, but I saw you had some code that added or changed a class.

    I was thinking that I could create to other columns, number, one could sum the stars clicked and the other number of clicks making it easy to do the math for each item.

    I remember you have the other script to update fields in the list view so I know this can be done just beyond my skill set.

    I know your busy and I will continue to hack away at this. any help or advice would be appreciated.

    thanks again

    1. Update, I have a way, using another calculated field to update the class for the stars.
      [sourcecodelanguage=”javascript”]
      =”…

      StarClass formula
      [sourcecodelanguage=”javascript”]
      =IF(NOT(ISERROR([stars]/[votes])),IF(ROUND([stars]/[votes],0)=5,”fivestar”,IF(ROUND([stars]/[votes],0)=4,”fourstar”,IF(ROUND([stars]/[votes],0)=3,”threestar”,IF(ROUND([stars]/[votes],0)=2,”twostar”,IF(ROUND([stars]/[votes],0)=1,”onestar”))))),”nostar”)

      So now I am trying to fiugure out how to sum stars (in one column) and count votes(in another column) while at least limiting them to one vote per browser session

    2. Larry,
      Sorry, but i cannot help you with this as it is a bit complex to look into. I have plans on updating the solution with the 5 star rating system, but there are so little time…

      There are probably not much help in me saying this, but i would have handled all this within the original rating script, possibly using “-2”, “-1”, “0”, “1”, “2” as rating and then averaged it to display the correct star combination. The number of votes could be a mouseover or a text behind the stars.

      Alexander

    3. that makes sense. the first time I wnet thru ur rating script I was trying a differnt angle and i was not having success. At least I have a new approach.

      thanks again

  108. Alex

    We have 2 date fields i.e. Start Date and End Date. I want to validate End Date field using onblur event. Validation should check the End Date should not less than Start Date.

    Please let me know how can I do this, as I newbie in programming, working on this from last 2 days, still not able to resolve it.

    Ple…………..ase help me out

    1. Hi,
      Drop this code in a CEWP below the NewForm. Change the fieldInternalNames to match your date fields. The code executes on click on the OK button and aborts save if it triggers.

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      function PreSaveAction(){
      var fromDate = $(fields['StartDate']).find('input:first').val();
      var toDate = $(fields['EndDate']).find('input:first').val();
      // Validation
      var fd = new Date(fromDate); // requires the fromDate variable to be in the format mm/dd/yyyy format 
      var td = new Date(toDate); // requires the toDate variable to be in the format mm/dd/yyyy format 
      	if(td<fd){
      		alert(""EndDate" must be greater than "StartDate"");
      		return false; // abort save
      	}else{
      		return true; // Validation OK - save item
      	}
      }
      
      function init_fields(){
        var res = {};
        $("td.ms-formbody").each(function(){
      	  if($(this).html().indexOf('FieldInternalName="')<0) return;	
      	  var start = $(this).html().indexOf('FieldInternalName="')+19;
      	  var stopp = $(this).html().indexOf('FieldType="')-7; 
      	  var nm = $(this).html().substring(start,stopp);
      	  res[nm] = this.parentNode;
        });
        return res;
      }
      </script>
      

      Alexander

    2. with the date function here is there a way to build into this a way to default the enddate. What i mean by default is when I click the date picker icon the calendar date in the popup defaults to what was selected in the startdate?

      If pick a startdate for end of year, I have to navigate thru the enddate the same way. Making it default to the startdate that was selected would just simplify it.

    3. Hi Larry,
      I’m not sure how to “hack” the default date picker to default to this date, but it’s easy to insert the “start date” in the “end date” field, and when the user clicks the datepicker icon, the date will be “defaulted” to the “start date”.

      Like this:

      var fromDate = $(fields['StartDate']).find('input:first').val();
      $(fields['EndDate']).find('input:first').val(fromDate);
      

      Alexander

    4. Thanx A, this was the direction I was leaning. So how can this be modified to change the end date when start date is change? is this fired off with a click function?

    5. i just found out with an alert that the date value doesnt change until the save. Setting date 2 = to date 1 wont work. there has to be another way to set the val of date 2 with the changed val of date 1 before the save. is there a way to use the existing function and write to both fields?

  109. I hate to bother you with this but I cannot figure it out. I have number fields. They hold IDs. I dont want any numeric punctuation added. No commas, no decimals etc.. I know how to create a calculated formula to remove all this, but I am hoping to avoid this route. I really only need this applied in the list view, but every string replace technique I have applied failed. The following is my last attempt. Can you advise what I am missing?

    <script type="text/javascript" src="/sites/learning/Scripts/jquery-latest.min.js"></script>
    <script type="text/javascript"> 
    $("td[class='ms-vb2'] > div").each(function() {
    var inner = $(this).innerHTML;
    $(this).inner.replace(/[^0-9]/g,'');  
    //OR
    $(this).inner.replace(/,/g,"");
    }
    </script>
    
    1. Hi,
      You had the syntax a bit wrong:

      $("td[class='ms-vb2'] > div").each(function() {
      	var inner = $(this).html();
      	$(this).html(inner.replace(/[^0-9]/g,''));
      });
      

      Alexander

  110. Hi Alex,

    This is really great blog!! awesome work and i am big fan of this site, i check everyday and look at the things and learn , but i need something that i cannot find any where. Let me explain what i need..

    I have a list with a people picker and a field called email address, i want to get the email address populated automatically depending the person on people picker ( single user). I know that i need to get user information from profile, but i am not a programmer and there i need your help.

    I know you are really busy but please spotlight when you have time.

    Thanks in Advance.

    1. A helped me with this script that pulls data from people picker fields and auto populates people picker fields, this could easily be set to email. I hate to repost it, but I can’t remember where it was posted.

      You need scripts from this site, jquery and a few others.
      AccessUserProfileInWSS should have instruction where to get them all.

      <script type="text/javascript" src="/sites/learning/Scripts/jquery-1.3.2.min.js"></script>
      <script type="text/javascript" src="/sites/learning/Scripts/interaction.js"></script>
      <script type="text/javascript" src="/sites/learning/Scripts/stringBuffer.js"></script>
      <script type="text/javascript" src="/sites/learning/Scripts/AccessUserProfileInWSS.js"></script>
      

      source list – where data is stored = var arrOfFieldInternalNamesInManagerList = [‘Manager’,’Manager2′];

      target list – list to populate = var arrOfFieldInternalNamesInThisList = [‘Manager’,’Manager2′];

      <script type="text/javascript" src="/sites/learning/Scripts/SetPeoplePicker.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      // FieldInternalNames from 'ManagerList'
      var arrOfFieldInternalNamesInManagerList = ['Manager','Manager2'];
      // FieldInternalNames from this list to writ the data back to
      var arrOfFieldInternalNamesInThisList = ['Manager','Manager2'];
      // Hide all the people picker fields
      $.each(arrOfFieldInternalNamesInThisList,function(i,fin){
      	$(fields[fin]).hide();
      });
      // Get managers for current user - "_spUserId" is current user
      // listname,fieldinternalname, , 
      var userAndManager = getManager('ManagerList','User',_spUserId,arrOfFieldInternalNamesInManagerList);
      
      // Wait until page has finished loading, then fill the manager fields
      $(document).ready(function(){
      	$.each(userAndManager,function(i,item){
      		var split = item.split(';#');
      		var userID = split[0];
      		var dispName = split[1];
      		var ui = getUserInfo(userID);
      		// Set the people pickers value on load
      		setPeoplePicker(arrOfFieldInternalNamesInThisList[i],ui.Name);
      	});
      });
      
      // Function to set the people picker value - slighly modifid to handle hidden fields
      function setPeoplePicker(FieldInternalName,loginName){
      var field = $(fields[FieldInternalName])
      	if(field.find('.ms-inputuserfield').css('display')!='none'){
      		// IE
      		field.find('.ms-inputuserfield').html(loginName);
      		field.find('img:first').click();
      	}else{
      		// FF
      		field.find("textarea:first").val(loginName);
      	}
      }
      
      // Custom function to pull managers from anoher list based upon current users ID
      function getManager(listNameOrGuid,FieldInternalName,userId,arrOfViewFields){
      	wsBaseUrl = L_Menu_BaseUrl + '/_vti_bin/';
      	var query = "<Where><Eq><FieldRef Name='" + FieldInternalName + "' LookupId='True'/><Value Type='User'>" + userId + "</Value></Eq></Where>";
      	var res = queryItems(listNameOrGuid,query,arrOfViewFields,1);
      		var item = res.items[0];
      		var ret = [];
      		$.each(arrOfViewFields,function(i,fin){
      			ret.push(item[fin]);
      		});
      		return ret;
      }
      
      function init_fields(){
      var res = {};
      $("td.ms-formbody").each(function(){
      if($(this).html().indexOf('FieldInternalName="')<0) return;
      var start = $(this).html().indexOf('FieldInternalName="')+19;
      var stopp = $(this).html().indexOf('FieldType="')-7;
      var nm = $(this).html().substring(start,stopp);
      res[nm] = this.parentNode;
      });
      return res;
      }
      </script>
      

      this script hides the user and manager fields, and auro populates them. you can unhide the fields and populate different data.

  111. Your stuff is awesome, I have an issue and are curious as to what you would recommend for this.

    Scenario: organize list items in folders where name is field value entered into newform.aspx

    Requirements: create list items in correct folder without user intervention,

    Considered using SP presave action to create folder based on list field, not sure how to add item to that folder.
    Folder path is populated in query string with ?RootFolder=/Lists/List/[Folder], List field is single line text

    Any help is appreciated

    Thanks, Joe

    1. Why do you need folders? There are many arguments out there on the pros and cons of folders. Personally I feel the Meta data can handle 90% of this concern and is very easy to implement.

      One problem you may have with the creation of folders by end users is the lack of consistency you will have from user to user. This could become a maintenance nightmare after you have 100’s of folders created in a library. If you restrict the naming convention they you may run into the duplicate folder names.

      There are also topics that folders interfere with custom views. I am not 100% convinced of this, but it does present problems. Go with the Meta data it is much easier to regulate and standardize.

    2. Hi Joe,
      I support Larry’s comment above. Though it may be possible, it will rather quick get “dirty”. If you need any more, please post further comments on this thread.

      Alexander

  112. I have an observation form with 6 radiobutton fields. the options for all 6 fields are the same:
    – complete – Not complete – Partial complete – N/A

    on the newform or edit as the user makes selections I want to tabulate selections in 4 additional fields (Number). One named for each of the options.
    – complete – Not complete – Partial complete – N/A

    I can set a field value with pieces of your scripts. I am not sure how to trigger the count when an option is selected.

    sComp = (++sComp);
    $(fields['Complete']).find('input:first').val(sComp);
    
    sNC = (++sNC);
    $(fields['NC']).find('input:first').val(sNC);
    
    sPC = (++sPC);
    $(fields['PC']).find('input:first').val(sPC);
    

    this is only half. How can I count the Complete field each time complete option is selected from any of the questions. And how can I decrease the count when Complete is deselected.

    Not just compelte, all options for all fields.

  113. Hi Alexander:
    (related to your vLookup solution) –

    I need to be able to import/paste a list of employees where one of the fields is the employee number. I can’t import it as a number because I need the leading zero’s (mine is 007064).

    I would prefer importing this number into a Person or Group field, “automatically” prompting the List to authenicate it against my users.

    Once this employee number triggers the authentication, I can filter by [me].

    Any ideas how to import a number and then trigger an “automatic” Person or Group authentication?

    As always, Thanks-

    Charlie Epes
    Buffalo, NY

    1. you can handle this a couple of ways. First is the the number field can be a single line text. this would allow import of leading zeros. If you can go with a single line field and you need a number. add a calcualted field to read the number and set the fiels to the length you need which will add leading zeros like this:

      =TEXT([numberField],"000000") 
      
    2. Hi Charlie,
      My first thought is to use excel (and vLookup) to find the loginName for the users (matched from another source/sheet) and to paste the loginNeme in a SharePoint datasheet view (just set the people picker to expect loginname in the list settings).

      This will be far easier then using javascript to match the employe number with loginName.

      Alexander

  114. New request I believe it is fairly simple. By the way congrats on your article making it to EUSP.

    Again I hacked another piece of your code to color the background of the heading of a grouped view.

    // Set color of "Total" rows for groups/sub-groups
    $("td.ms-vb2").each(function(i){ 
    	i = i+1;
    	$("tbody[id^='aggr'] tr").addClass('bColor');
    });
    

    running the code like this tasks the resources so i modified it like this

    $("tbody[id^='titl1-'] td").addClass('aColor');
    

    this applies color to the first and second level grouped items. I would like to apply a differnt color for the second level, but I am not sure how. I have not been able to find a way to distinguish the two levels apart. any suggestions?

    1. Thank you,
      I’m not sure if this is what you try to achieve, but try this:

      // First group
      $(".ms-listviewtable td.ms-gb2").addClass('dummyClassRed');
      // Second group
      $(".ms-listviewtable td.ms-gb").addClass('dummyClassGreen');
      

      Replace the “dummuyClass with the class you want to use.

      Alexander

  115. Hello.

    I have a list with about 25 columns which is too wide to fit horizontally on most monitors.

    Is there a way to dynamically collapse and expand columns in a SharePoint list (using jQuery) so the user can choose what columns to view?

  116. Alex great work as normal, I have a page with multiple lists that are filtered I would love to be able to hide the list if the filter returns no records, is it pauseable?

    Tony

  117. I have another request. I have been hacking away at a piece of your code from the rating script. I want to hide a column, multiple columns. In that script you hide the ID column. I also saw another post similar to this. I even tried that code but no luck. this only hide the header cell

    $(".ms-viewheadertr th").each(function(){  
                 if($(this).find('table:first').attr('name')=='StatusFlag'){  
                     IDcolIndex = $(this).attr('cellIndex');  
                         $(this).addClass('HideMe');  
                 }  
             });  
                      $(".HideMe").hide(); 
    

    what do I not see? what am I missing to hide the column StatusFlag

    1. The code is for the table header only. You must iterate over all the tr’s in the table and hide the td where ‘cellIndex’ equals IDcolIndex.

      You find the code in the posts you refer to, just search for “cellIndex” in the code.

      Alexander

    2. I went through the code some more and was able to find what I think you were talking about. I made a few modifications and put this together . Now I’m getting an error on the page

      ‘g_ExpGroupState’ is undefined

      //ref to jquery
      <script type="text/javascript"> 
      fields = init_fields();
      
      function HideColumn(FieldInternalName,hideIdCol) {
      hideId = hideIdCol;
      intName = FieldInternalName;
      	// Find index of column
      	$(".ms-viewheadertr th").each(function(){
      		if($(this).find('table:first').attr('name')==intName){
      			IdColIndex = $(this).attr('cellIndex');
      			// Hide column header
      				if(hideId){
      					$(this).remove();
      				}
      		}
      	});
      
      	$("table.ms-listviewtable tbody:not([id^='aggr']) >tr:has(td.ms-vb2)").each(function(){
      		var thisTd = $(this).find("td[cellIndex=" + colIndex + "]");
      		var thisIdColumn = $(this).find("td[cellIndex=" + IdColIndex + "]");
      		var thisId = thisIdColumn.text()
      		if(hideId){
      			thisIdColumn.remove();
      		}
      	});
      }
      
      function init_fields(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      HideColumn('StatusFlag',true);
      </script>
      

      I know I am close because the header is hidden, but I have lost all data in my grouped view. Headers are there, just nothing below them.

      can you see anything obvious I may be missing?

    3. So I have it working now and I added a checkbox to work on the hide show. It seems the the function only fires once on the click function for a checkbox. Do you know how to trigger the event for each click of the checkbox?

    4. How does the code for the checkbox look? – my first thought is that you must use “click” and not “change”, and check the myCheckbox.attr(‘checked’) for true/false.

      Alexander

    5. thanks, I have been back and forth with change and click, not getting either to work like I want. Here is my function and checkbox

      <script type="text/javascript">  
      $(document).ready(function() { 
      	$("#cbStatus").click(function () { 
      		if ($('#cbStatus:checked').val() !== undefined) { 
      			HideColumn('Status',false);
      		} else { 
      			HideColumn('Status',true);
      		} 
      	}); 
      }); 
      </script>
      <input type="checkbox" id="cbStatus" name="cbStatus"  checked />status <br />
      

      this seems to fire only once. I also tried by checking the attr but then it only fires once as well

      $(document).ready(function() { 
      	$("#cbStatus").click(function () { 
      	                if ($('#cbStatus').attr('checked') == true) {
      			HideColumn('Status',false);
      		} else { 
      			HideColumn('Status',true);
      		} 
      	}); 
      }); 
      </script>
      <input type="checkbox" id="cbStatus" name="cbStatus"  checked />status <br />
      

      can you see what I am not?

    6. Here is a working code example (my column is named “HideMe”:

      <!-- The name property is the FieldInternalName of the column -->
      <input type="checkbox" id="cbStatus" name="HideMe" onclick="javascript:HideColumn($(this))"/>HideMe
      <script type="text/javascript" src="../../Javascript/jquery-1.4.min.js"></script>
      <script type="text/javascript">
      
      function HideColumn(obj){
      fin = obj.attr('name');
      toggleCol = obj.attr('checked');
      	// Find index of column
      	$(".ms-viewheadertr th").each(function(){
      		if($(this).find('table:first').attr('name')==fin){
      			IdColIndex = $(this).attr('cellIndex');
      			// Hide column header
      			if(toggleCol){
      				$(this).hide();
      			}else{
      				$(this).show();
      			}
      		}
      	});
      	
      	// If col is not found - return
      	if(typeof(IdColIndex)=='undefined'){
      		alert("The column with FieldInternalName ""+fin+"" is not in the view.");
      		return;
      	}
      
      	$("table.ms-listviewtable tbody >tr:has(td.ms-vb2)").each(function(){
      		var tdToToggle = $(this).find("td[cellIndex=" + IdColIndex + "]");
      		if(toggleCol){
      			tdToToggle.hide();
      		}else{
      			tdToToggle.show();
      		}
      	});
      }
      </script>
      

      Alexander

  118. I have a request
    I have 5 content types for a list Eg: Content Type A, Content Type B, Content Type C, Content Type D, Content Type E
    and I have 4 or more Security groups, say as Group P, Group Q, Group R, Group S

    Now my scnario is Group P should see Content Type A,
    Group Q should see Content Type A,Content Type B,
    Group R should see Content Type D,Content Type E,Content Type C
    Group S should see ALL Content Types data

    Is there is a possibility,.. ?

    1. Yes, ther are two main script that come to mind from this forum that you could use to achieve this result.
      Identify content type to execute content type specific code
      https://spjsblog.com/2009/11/20/identify-content-type-to-execute-content-type-specific-code/

      and

      Showing or hiding list fields based on membership in a SharePoint group
      https://spjsblog.com/2009/09/20/showing-or-hiding-list-fields-based-on-membership-in-a-sharepoint-group/

      these two scripts in combin ation can achieve what you need

  119. Alex great work as normal, I have a page with multiple lists that are filtered I would love to be able to hide the list if the filter returns no records, is it pauseable?

    1. Hi,
      Try this in a CEWP below the webparts to hide:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.min.js"></script>
      <script type="text/javascript">
      $("div[id^='WebPartWPQ']").each(function(){
      	if($(this).html().match(/There are no items to show in this view of the/)!=null){
      		$(this).hide();
      	}
      });
      </script>
      

      Alexander

  120. you made a post to change external links. I an trying to modify this to change an attribute. the problem is I dont have access to the parent frame because it is hosted by a vendor. ther is an email link in the parent for help. it is a mailto link. I was hoping there is a way to change this through script. this is what I have so far

    $("td.hf-logoffmailicons a", top.document).each(function(){
      var href = $(this).attr('href');
    
      if($(this).attr('href').match('mailto:')==null){
        $(this).attr('href').replace(/mailto:/g,"");
      }
    });
    

    Through a UI I can change the email address, but I do not have access to the link attributes.

    Is there a way to access the parent frame of an iframe and remove the “mailto:”?

    1. I’m not sure, but if you wrap he code like this:

      $(document).ready(function(){
          // Run your code here to have it trigger after the "document" has loaded
      });
      

      Does it help?

      Alexander

  121. I have a simple request. I would like my attach file button open up an excel spreadsheet. once they fill it out, then it saves the way a normal attachment does.

    In a nutshell I need the attach file button to work similar to how the new item work from a doc library that has a pre-defined word doc template.

    1. Hi,
      I’m afraid this is not a simple request… The “add attachment” is based on upload from the users hard drive. A spreadsheet would have to be saved locally by the user and then uploaded.

      I have no immediate solution to this request.

      Alexander

  122. Hello

    I have dropdown field in newform/editfor. This drop containing US States and “Select State” as first option. It is required field. I want that If user doesnt select any state, leave “Select State” as default value, my required validator message should display.

    is this possible

    Elstone

    1. Hi,
      Add this code below NewForm and EditForm:

      <script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      function PreSaveAction(){
      var myDropdown = $(fields['MyDropdown']).find('select');
      var myDropdownVal = myDropdown.find('option:selected').text()
      	if(myDropdownVal=='Select State'){
      		myDropdown.focus();
      		alert("You have to select a state from the list...");
      		return false;
      	}
      	return true;
      }
      
      function init_fields(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      </script>
      

      Alexander

  123. Hi Alexander

    We have a form on which we have three person fields. What we would like to do is make fields on the form read only based on which person field they are included in. Is this possible?

    Thanks

    Andrew

    1. How are you setting up the people pickers? I am trying to understand how you know a person is in a pp field and not all. Will the field be populated with a value? If so I could see easily grabing the value.

      Playing with some simple jquery and hacking some of A’s code here is the code to hide a people picker. if you add it to a function that checks field values and compares against user. the following posts could help you identify the user for comparison.

      Autocomplete for SharePoint people picker

      Link to fill user login name in people picker

      <script type="text/javascript" src="../../JavaScripts/jquery-latest.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      $(document).ready (function() {  
       var field = $(fields['PeoplePicker'])  
      	if(field.find('.ms-inputuserfield:visible').length>0){  
      		// IE  
      		field.find('.ms-inputuserfield').attr('disabled',true); 
      	}else{  
      		// FF  
      		field.find("textarea:first").attr('disabled',true);
      
         
      	}
       field.find('.ms-usereditor td:has(a)').hide(); 
      });  
      
      function init_fields(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      </script>
      
    2. Sorry I don’t think I explained myself very well. What we have is three people picker fields employee, manager, director that would be filled out on the newform. Once somebody goes in to edit the form we would like each person to be able to edit certain fields.

      So for example the director would only be able to edit a specific number of fields and the rest be read only. The same would apply to the manager and employee.

      Does this make sense?

      Thanks

      Andrew

    3. Thanks Larry we use this feature elsewhere but in this instance on the edit form we require users who are filling in the form to be able to see the fields that have been entered by other users. This means we require to make the fields read-only and not hide them.

    4. I apoligize, instead of hiding the field set the attribute to readonly. I know there isnt a script readily available here. At times I have found myself taking pieces of code from many of A’s posts and putting them together for my solution.

      Again I apoligize, I know there isnt your exact request visible, but there are close representations that you can piece together or modify if you have some development background. I would be willing to help you if you want to try.

    5. Using the logic from this newly added post: Get field value for all SharePoint FieldTypes or set field as read only in EditForm

      Here is an example:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/interaction.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/stringBuffer.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/GetFieldValueOrSetAsReadonly.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      userListGuid = '570D772F-0EAB-45A8-8C54-9CCD4EC6A0AF';
      userListBaseUrl = '';
      myPeoplePickerFin = 'MyPeoplePicker';
      
      $(document).ready(function(){
      	var myPeoplePicker = $(fields[myPeoplePickerFin]).find('.ms-formbody').find("div[id='divEntityData']");	
      	if(myPeoplePicker.length>0){
      		var isResolved = (myPeoplePicker.attr('isresolved').toLowerCase()=='true')?true:false;
      		if(isResolved){		
      			var login = myPeoplePicker.attr('description');
      			var uiObj = getUserInfoFromLogin(login);
      			if(_spUserId!=uiObj.ID){
      				alert("You are not the person in the field named ""+myPeoplePickerFin+"".");
      				// Make some fields readOnly
      				var arrToMakeReadOnly = ['Title','MySelect','MyPeoplePicker'];
      				redOnlyField(arrToMakeReadOnly);
      			}			
      		}
      	}
      	return true;
      });
      
      function getUserInfoFromLogin(UserLogin){ //
      wsBaseUrl = userListBaseUrl + '/_vti_bin/';
      var retObj = {};
      var arrOfFields = ['ID','Name','Title','EMail','Department','JobTitle','Notes','Picture','IsSiteAdmin',
      				   'Created','Author','Modified','Editor','SipAddress','Deleted'];
      
      var query = "<Where><Eq><FieldRef Name='Name' /><Value Type='Text'>" + UserLogin + "</Value></Eq></Where>";
      var res = queryItems(userListGuid,query,arrOfFields,1);
          if(res.count>0){
      	    for(i=0;i<arrOfFields.length;i++){
      	    	retObj[arrOfFields[i]] = res.items[0][arrOfFields[i]];
      	    }
             	return retObj;
          }else{
              for(i=0;i<arrOfFields.length;i++){
          		retObj[arrOfFields[i]] = "User with id " + UserLogin + " not found.";
          	}
      		return retObj;
      	}
      }
      </script>
      

      Alexander

    6. Hi Alexander

      We are trying to use this script alongside the fields side-by-side script but I cannot get them to work together. Any ideas or suggestions.

      Thanks

      Andrew

  124. is there a way to create an assessment type functionality? Your HTML tooltip displays text on hover from another list. is there a way to create an intake that can compare data from another list (questions, questionID, answerA,answerB,answerC.., correct answer) and on submission have it return user selections in addition to a right/wrong answer, pass/fail status column(s)?

    1. Hi,
      Thank you for helping out answering questions.

      About the request: It is possible, but i think this would be a bit to specialized and a bit to much work to post here. If you set up a more detailed description and email it to me, i might take another look at it.

      Alexander

  125. In a document or form library there is a function you can access in the settings called “Relink documents to this library”. I have a large need for this when dealing with InfoPath forms and republishing. This page allows you to see the documents in the library and the template path. Each item has the option to be selected, then relinked. By default you have to select one at a time or click each checkbox.

    I built a “select all” webpart and added it to the page and it works perfectly. The view is set to 100 items at a time with paging. There is no way using the UI to change this. However; I can change the page source and manually change this number.

    I do not like making the change this way because it removes the page from SharePoint and make it like any webpage by unghosting it.

    What I want to do is add a simple script that will replace the rowlimit of 100 with another number but I can not seem to access it. In the Forms/repair.aspx source this is the part of the code i need to change
    [sourcecode]
    &lt;RowLimit Paged="TRUE"&gt;100&lt;/RowLimit&gt;

    can it be done using jquery?

    1. I do not think it is possible that way, as the view is specified in the list schema and any modification after the page has loaded has no effect.

      However you can modify the view from within SharePoint with a small “hack”:
      Get the view GUID from the relink view (view source and search for “ctx.view”), copy with the braces like this {439B16F7-B588-4E87-9558-7B33E9E5FADF}.

      Then go to another view in that list, click “modify this view”, then replace the view GUID in the URL at “&View=” and reload the page.

      Alexander

    2. one more question on the relink page. I have a decent select all function. I have been able to add it to the tool bar and just below the relink label for that column. What I want to do is hide the column title “Relink” and replace it with my string “str” for select all. Either I hide the entire cell or I get an error. this will append the “Relink” text
      [sourcecode]
      $("th.ms-vh2-nograd").append("<div style=’font-size:7pt’>"+str+"</div>");

      what will replace? I cant figure out the syntax.

    3. I have almost completed this task on the relink page. I can write a checkbox in the relink column header, but I can’t get it to format clean. I tried to do a string replace with jquery but not successful. I finally got a solution to work.

      can you take a quick look and let me know if there is a better way?

      all I want to do is hide the text “Relink” and replace it with my “str”

      $("TH.ms-vh2-nograd:contains('Relink')").hide().after("<TH class='ms-vh2-nograd'>"+str+"</TH>");
      
  126. Thanks for previous info. New general knowledge request. I have an intake using several of your scripts. The newform and editform scripts are almost identical (hide content type field only difference). The new form works perfectly. When I edit an item some of the scripts appear not to work. When I set the page into edit mode, they begin working. What can cause this to occur?

    1. I figured it out. What I have been doing for simplifying maintenance I add all my external scource file links into a text file, link the CEWP to the text file.
      I do the same thing for my functions, I have one for the NewForm and another for the EditForm, both share the source file links. Much easier to edit in a text file than a CEWP. What I found was the source file links were not loading in the page until I put page in edit mode. I don’t know why. I deleted that CEWP added a new one and recreated the link to the file. works fine.

      thanks again

  127. Hello

    I want to implement following process in “Delete Item” from ECB Menu and from fispform.aspx form tool.

    1. Can I set redirection whenever user click on “Delete Item” from ECB menu or Form Tool bar

    2. Is this possible if we can add one more button/option in Form Tool Bar of “dispform.aspx” thne clicking on this new page redirect with page source as query string to another page.

    Please help me

    1. Hi,
      For modifying the delete function i would recommend an event handler and not javascript. Even though you can override the default functionality when deleting, this must be added to every view of the list.

      To add a new menu option use this code in a CEWP below the form:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      $("table.ms-toolbar:first >tbody tr:first").find("td[width='99%']").before("<td class='ms-separator'>|</td><td class='ms-toolbar' style='white-space:nowrap'><a href='/SomeWhere/SomePage.aspx?source="+location.href+"'>Go somewhere</a></td>");
      </script>
      

      Alexander

  128. Hi Alexander

    Is it possible to use the readonly field script I requested above with your fields side-by-side solution? I don’t seem to be able to get them to work together.

    Any help would be appreciated.

    Thanks

    Andrew

    1. Everything is possible, but i have not had the time to look at it. I think it will require modification, but is possible.

      Try to change the order of calling the scripts as it may be important.

      Make a go at modifying it and let me know how it goes.

      Alexander

    2. Hi Alexander

      I have played around with re-ordering the scripts but have had no joy getting them to work together. It just repeats what is contained it the first field and repeats it across when they are made read-only.

      Thanks

      Andrew

  129. Hi Alexander,

    after having implemented a number of your great scripts, two new thoughts crossed my mind. Well, they are not exactly my ideas but have been inspired by your scripts.

    To start with an easy one (maybe), we are using document libraries with grouped views to display data to the customer. With the help of some other script I managed to get rid of the “Group by part left of the ‘:'” (I’ll gladly provide the script if you are interested), which gives a much cleaner look. Now I would like to limit the number of displayed items per group to “x”, or maybe even depending on the group to “x or y”, but SP only allows to set a limit for all items on a page.

    It’s a bit like “display only the last x|y items” for group “x” or “y”.

    The second one is related to list views, I got this idea when I saw your article about column visibility. As of today, we are using an excel report to show report data for the last four calendar weeks. The data and the “column” shift have to be done manually. With the column visibility article in mind I thought if it would be possible to have SP automatically ‘shift’ visible columns, thus showing the ‘current’ and ‘current-x’ calendar weeks?

    If you need further details on this let me know.
    regards,
    Chris

    1. Hi,
      Unfortunately my kitchen renovation has eaten away from my “blog time”. I cannot come up with a solution right now, but if you look at my other scripts that “interact” with a grouped view, you can start off by yourselves.

      The trick would be to limit the number of “tbody” elements rendered (hiding or removing the excess).

      Your other question is related to this comment You might create something based on this solution.

      Alexander

  130. Good Day A,

    Some time back you helped me with the syntax to hide commas in a list view. works perfectly. I would like to take it one step further. for the headers, where we can sort and filter, the comma still displays here.

    Can comms (or special characters) be hidden or removed from the filter menu of a column header?

  131. Hi All,
    This is Krishna and i am new to this blog.. And coming to point, my requirement is: When we want to view a particular item in a task list, just we will click on item and the record is shown in DispForm.aspx. If we want to view any other record again we should go to task list and click on the required item record.

    My requirement: I need to create a “Next” link button on DispForm so that when user the user can view the next record without goin to tasklist again and clicking on next record.

    Any help/solution/suggestions will be grateful.

    1. here is a proof of concept. I borrowed this script from Christophe at blog.pathtosharepoint.com and made some modifications. the result has a prev and next functionality. with some work you can make it fit your needs.

      the original function displayed the item ID either at the top of the form or the bottom, but not both. The bottom is commented out, but you can swap them around.

      <script type="text/javascript">
      //
      // Item ID in DispForm.aspx and EditForm.aspx
      // christophe@pathtosharepoint.com
      //
      
      function DisplayItemID() {
      	var regex = new RegExp("[\?&]"+"ID"+"=([^&#]*)");
      	var url = location.pathname;
      	var qs = regex.exec(window.location.href);
      	var TD1 = document.createElement("TD");
      	TD1.className = "ms-formlabel";
      	TD1.innerHTML = "<h3 class='ms-standardheader'>Issue ID</h3>";
      	var TD2 = document.createElement("TD");
      	var prev = parseInt(qs[1]);
      	prev -= 1;
      	var next = parseInt(qs[1]);
      	next += 1;
      	//alert(url);
      	TD2.className = "ms-formbody";
      	TD2.innerHTML = "<b><a href='"+url+"?ID"+prev+"'>&lt;&lt; PREV</a></b> " + qs[1] + " <b><a href='"+url+"?ID"+next+"'>NEXT &gt;&gt;</a></b>"
      	//TD2.innerHTML = qs[1];
      	var IdRow = document.createElement("TR");
      	IdRow.appendChild(TD1);
      	IdRow.appendChild(TD2);
      	var ItemBody = GetSelectedElement(document.getElementById("idAttachmentsRow"),"TABLE").getElementsByTagName("TBODY")[0];
      	//Display as first form item
      	ItemBody.insertBefore(IdRow,ItemBody.firstChild);//first item
      	//Display as last form item
      	//ItemBody.appendChild(IdRow); //last item
      }
      //load function in SP
      _spBodyOnLoadFunctionNames.push("DisplayItemID");
      </script>
      

      let me know if you have any questions

    2. two more notes.
      1. I miss a set of “=” signs on line 21
      should be this

      TD2.innerHTML = "<b><a href='"+url+"?ID="+prev+"'>&lt;&lt; PREV</a></b> " + qs[1] + " <b><a href='"+url+"?ID="+next+"'>NEXT &gt;&gt;</a></b>"
      

      2. if the next or previous ID does not exist you will get an error. you may need to create a check that determines if the next ID exists. If not go to the next.

  132. Thanks larry..Thats realy good. But i need some modifications on that. i.e when we open first item and click prev button it is showing some junk values. If we are at first record and the user clicks on Prev button we should show a msg that its first record.

    One more important thing is i need the basic idea of this how u created and can u give description on this bcoz i knew javascript but i never used the methods and attributes u have used…Please help me on this k..

    Thanks
    K.K

  133. Hi this praba,

    Please advice / help me to build the below scenario.

    Scenario 1
    Batch update using Data view Web part and select all checkbox.

    1.In a data view web part
    2.Select records to be edited using checkbox
    3.Edit multiple records fields
    4.Click the update link to update all the records to sharepoint list.

    Scenario 2

    1.I have a custom form build using asp.net
    2.Populate same form with SharePoint list data’s
    3.And update from same form to SharePoint list.

    Please help me build the above scenarios,

    Millions of thanks in advance.
    Praba.

  134. Hi Alex:

    Please give some tips and advice to achieve the above Scenario 1 and 2, because I am very new this areas.

    Thanks
    Prabakaran

    1. Hi again,
      Sorry, but as i wrote above, this one is to complicated to create as a blog post.

      It’s possible, no doubt, but may take hours upon hours to create. Unless you can learn from this (and other) blogs and begin writing the scripts yourselves (and ask if you have specific issues), i cannot help you with this one.

      Alexander

  135. Hey A. Hope you’re well. I was trying to add a script to set the width of a text field. I can make it smaller with no problems. Trying to make it wider than 300px 400px can’t do on a new or edit form

    Any suggestions?

    1. Hi,
      try this using the function init_fields():

      // Title field
      $(fields['Title']).find('input').css({'width':'800px'});
      // Multiline plain text
      $(fields['Multiline']).find('textarea').css({'width':'800px'});
      

      Alexander

  136. Hi Alexander…. great job with your blog. Has been very useful so far.

    I wanted to ask if you have any solution for dynamic fields into another form.

    The idea is for example, fill a new form with a course information, and have fields with name and e-mail address. Then i can complete this two fields, and if i want i can press an “Add” button, so dynamically appears another 2 fields with name and e-mail, and so on.

    This 2 fields, should be saved on a diferent list, and be linked by his ID with the course information.

    Would it be possible?

    Regards,

    Nicolas

  137. I want to Hide “Site Actions”,”View All Site Contents” and “Sign in as Different User” for all the users who does not belong to “Administrator” group, How can I do this?

    1. Hi,
      I do not think javascript is the way to do this. The code would have to go on every page in the site.

      A feature or custom master page could be used (security trimming the controls). I’m not the guy to talk about regarding this approach, but here is how you could do it with javascript (place the code in the master page to load it in every page, or use SharePoint Infuser

      Use this post Showing or hiding list fields based on membership in a SharePoint group to learn how to get the list collection from a user. You will have to pull parts of the code and combine it with something like this:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      // Remove "Sign in as Different User"
      $("*[id$='ID_LoginAsDifferentUser']").prev().andSelf().remove();
      
      // Remove "View All Site Content"
      $("div.ms-quicklaunchheader").remove();
      
      // Remove "Site action"
      $("table.ms-siteaction").remove();
      </script>
      

      Alexander

  138. Hi Mr.Alexander,
    As per your instruction, i’m posting the request here. I have a long pending urgent requirement as below.
    I have a simple list with below mentioned columns(fields).

    1. Title 2. Part No. 3. Part Name 4. Model 5.Make 6.Comments

    While creating these columns, i have given some detailed information about these columns in the “description” field of the respective columns.
    As we all know, this description can be seen by users who have only “Edit Permissions” for the list.

    Requirement is, just to display this description as a tooltip when a “read-only” user of that list hovers the mouse on the column(field) in “DispForm.aspx”
    I have seen lot of solutions which are showing tooltip at items level for the list. But, here i want to show tooltip at “column(field)” level.

    Could you please check and help me on this?
    Awaiting for your reply with anticipation.
    Thanks in advance.

    1. Hi Mr.Alexander,
      Thank you very much for your prompt support.
      In my earlier request, i have mentioned wrongly as “DispForm.asp” by mistake.

      Actually, we need to show the tooltip in “AllItems.aspx” page of a list.

      When the user sees the SPGridView and hovers the mouse on the grid column header, we need to show “description” property information as tooltip of that particular column which was given at the time of the column creation.

      Information in the blog “Add HTML mouseover tooltip” is to show the tooltip at edit mode/Editform whereas we have to show column description as tooltip at “AllItems.aspx” page.

      Eagerly awaiting for your reply with anticipation.
      Thanks in advance.

    2. Hi Mr.Alexander,
      Could you please check for the “tooltip” requirement given as a reply to your response ?

      Awaiting for your valuable support
      Thanks in advance.

    3. This example does NOT pull the description from the field itself, but enables you to add the text directly in the script. This is a bit easier to implement. Look at the code and edit the variable “myTooltipObj” to match your columns and descriptions.

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script type="text/javascript">
      // Add custom tooltip on column header - Uses fields display name to identify the column
      var myTooltipObj = {'Title':'This is a custom tooltip for the Title column',
      					'Multi Line':'Tooltip for my multiline'}
      
      $(".ms-listviewtable th").each(function(){
      	var fieldDisplayName = $(this).find("table:first").attr('DisplayName');	
      	if(fieldDisplayName==undefined){
      		fieldDisplayName = $(this).text();
      	}
      	if(myTooltipObj[fieldDisplayName]!=undefined){
      		$(this).attr('title',myTooltipObj[fieldDisplayName]);
      	}
      });
      </script>
      

      Does this answer your request?

      Alexander

    4. Hi Mr.Alexander,
      Thank you very much for your reply.

      I have added your javascript script and implemented in my list.
      On click of my “list” link on QuickLaunch, list is displayed but the tooltip is NOT displayed on mouse hover to “title” column.

      I added a alert statement and checked. This alert is fired on only “page refresh” and not on Mouse Hover.

      Should i have to add anything else to fire mouse hover ?

      Could you please help on this?
      Thanks in advance.

    5. Hi Mr.Alexander,
      Thank you very much for your reply.

      I have added your javascript script and implemented in my list.
      On click of my “list” link on QuickLaunch, list is displayed but the tooltip is NOT displayed on mouse hover to “title” column.

      I added a alert statement and checked. This alert is fired on only “page refresh” and not on Mouse Hover.

      Should i have to add additional code anything to fire mouse hover ?

      Could you please help on this as i am very much new to jQuery?
      Thanks in advance.

    6. Hi Mr.Alexander,
      Yes, we have also done the same. But it was not showing the tooltip on hover the mouse on title column.

      After seeing your reply, again i went to my list and checked. When i have hovered the mouse with little bit space away for the column text “title” ( but within that column area), the custom tooltip is displayed.

      Hope this will work for any custom columns !

      Excellent work !!! Thanks for your prompt support !!!

      If i hover the mouse exactly on the word “title”, tooltip “Sort By Title” is being displayed.

      Still the below things are disturbing our minds.
      Could you please check and clarify below things for me?

      1) Is it possible to remove this MicroSoft standard tooltip (for both pre-defined and custom columns) ?
      2) How about “Pulling the description from the list schema” as you mentioned earlier, which was already given by us at the time of column creation.

      As we want to show the information given in the “description” property of the column given in add/edit mode, is it possible to show that information instead of our static information using the above procedure ?

      If the second approach is implemented, then we need not have to do anything extra work when a particular column’s description is changed.

      If it is not possible, then we will go by the way you have suggested above.

      Once again thank you very much for your support.

      Thanks in advance.
      Awaiting for your reply.

    7. Hi Mr.Alexander,

      Thank you very much for your prompt support.
      This is what i was expecting.

      Excellent Work !!!
      Thanks a lot for your valuable time spent on the same !!!

      Thank You.
      Saran

  139. Hi Alex,

    Do have any tips for using JQuery to Custom sort a lookup list? I’d like to do concatenate ID and Description in a lookup field.

  140. Hi Team:

    One of my column is to be unique.
    How to fill this requirement using Jquery to enforce uniqueness in any Single line of text column.

    Regards
    Praba.

  141. Hi Alexander,

    I have been using your solution for filter list by group membership. Recently we have a requirement to filter list by user profile, this has to be done because of some issues with “only their own” settings. would you be able to modify your function “filterListViewByGroupMembership” to filter view by userid/login id? tried to do it myself but i cant seem to filter it right. many thanks

  142. On the edit or disp form, is there a way to hide or remove commas from a number field? I have been able to do it in a list view, but not the forms.

    1. That work for the decimal, but not commas. I have an intake that user an emp id. it is easy to copy the id rather that type it, but this 9 digit field adds to commas. Is there a way to do a replace on these forms?

    2. The commas is the “thousand-separator” based on your regional settings. SharePoint will always add it to DispForm and to EditForm (as you said), but If the input is indeed text, why not convert the field type to text?

      It is quite easy to replace the commas, but if you do not need a script it would be even better.

      Alexander

    3. I do understand. For some time I have struggled with this field. Initially it was setup as text, but there are no id’s that are alphanumeric, yet we still have people that do not understand with their emp id is. So I converted to number. The delima I have now is if I go back to text, I need a script that will only allow numeric values, if I stay number field I need to strip the commas, lol.

      which, in your opinion is the best way to handle this knowing I will eventually have to add a script of some sort? which leaves the smallest footprint?

    4. you are the best. I think when we upgrade to MOSS there will be more emp info available, but for now we are stuck here. thanks for the quick turnaround.

  143. I was recently asked if wikis support bookmarks. With the research I have done it is supposed to be true. The first page I created with bookmarks worked perfectly. When I added updates, the bookmarks went from relative to absolute links and now they open the edit page. Going back to a script you wrote to modify href attributes in a web part I am trying to figure out how to remove the URL up to the “#” in a wiki page.

    <a name="top">TOP</a>
    
    
    <a href="#top">Back to top</a>
    

    turns into this

    <a name="top">TOP</a>
    
    
    <a href="http://pathtosite/EditForm.aspx?ID=2#top">Back to top</a>
    

    what is the easiest way to remove the URL up to the “#”? I can’t get it.

    1. Hi,
      Try this:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      $(".ms-wikicontent a").each(function(){
      	var thisHref = $(this).attr('href');
      	var index = thisHref.indexOf('#');
      	if(index>0){
      		$(this).attr('href',thisHref.substring(index));
      	}
      });
      </script>
      

      Updated 24.06.2010

      Alexander

    2. along this similar line. Within the wiki, which I dont believe matters. I say not matters because I have had the same issue using a CEWP. I have created a unordered list for navigtion. it is layed out horizintally. I want its position fixed. CSS wont work. I is enclosed within a div like this,
      [sourcecode]
      <div id="menu">
      <ul>
      <li><a href="#a"><span>Alpha</span></a></li>
      <li><a href="#b"><span>Beta</span></a></li>
      </ul>
      </div>

      How can I get this to have a fixed position when content on the page scrolls?

    3. Update: The bottom solution is IE only…

      My initial suggestion (but look below for an easier method):

      <div id="myCustomMenu">
      <ul>
      <li><a href="#a"><span>Alpha</span></a></li>
      <li><a href="#b"><span>Beta</span></a></li>
      </ul>
      </div>
      <script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      
      // Parameters are: divID,startPositionTop, startPositionLeft
      scrollMe('myCustomMenu',200,800);
      
      // Trigger on scroll
      $(window).scroll(function(){
      	scrollMe();
      });
      
      function scrollMe(divId,topPos,leftPos){
      	if(divId!=undefined){
      		myCustomDiv = $("#"+divId);
      		myCustomLeft = leftPos;
      		myCustomTop = topPos;
      	}	
      	var st = $(window).scrollTop();
      	st+=myCustomTop;
      	myCustomDiv.css({'position':'absolute','top':st,'left':myCustomLeft});
      }
      </script>
      

      Never mind that script – it is not necessary to use a script… I still have a lot to learn about CSS:
      Update: This solution is IE only…

      This is the easiest method

      <style type="text/css">
      .divPositionAbsolute {
      	position:relative;
      	top:expression(this.offsetParent.scrollTop);
      	}
      </style>
      
      <div id="myCustomMenu" class="divPositionAbsolute">
      <ul>
      <li><a href="#a"><span>Alpha</span></a></li>
      <li><a href="#b"><span>Beta</span></a></li>
      </ul>
      </div>
      

      I learned this from this article about frozen headers in a list view: Scrolling View with Frozen Header

      Alexander

    4. great job. Much further than I was able to get. The first solution worked the best except for the alignment. The top navigation (list)sometimes falls on the text when navigating.

      the second script i have tried several different ways to implement. On the wiki page I added a CEWP with the style and list. it sits at the bottom of the wiki and does not scroll or move to the top. here is the code in the CEWP

      <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-latest.min.js"></script>
      <script type="text/javascript">
      // bookmark script
      $(".ms-wikicontent a").each(function(){
      
      	var thisHref = $(this).attr('href');
      	var index = thisHref.indexOf('#');
      	if(index>0){
      		$(this).attr('href',thisHref.substring(index));
      	}
      });
      </script>
      <style type="text/css">
      /* horizontal navigation */
      #myCustomMenu {
      position:relative;
      top:expression(this.offsetParent.scrollTop);
      }
      #myCustomMenu ul {
      margin: 0;
      padding: 8px 0 0 0;
      list-style: none;
      }
      #myCustomMenu li {
      display: inline;
      margin: 0;
      padding: 0;
      }
      #myCustomMenu a {
      float: left;
      background: url("/sites/globalmp/wikiTestLinks/left.png") no-repeat left top;
      margin: 0;
      padding: 0 0 0 6px;
      text-decoration: none;
      font:8pt verdana normal;
      }
      #myCustomMenu a span {
      float: left;
      display: block;
      background: url("/sites/globalmp/wikiTestLinks/right.png") no-repeat right top;
      padding: 6px 9px 4px 4px;
      color: #FFF;
      }
      
      /* Commented Backslash Hack hides rule from IE5-Mac */
      #myCustomMenu a span {
      float: none;
      }
      /* End IE5-Mac hack */
      #myCustomMenu a:hover span {
      }
      #myCustomMenu a:hover {
      background-position: 0% -42px;
      }
      #myCustomMenu a:hover span {
      background-position: 100% -42px;
      }
      </style>
      <DIV id="myCustomMenu" > 
      <UL>
      <LI><A href="#a"><SPAN>A</SPAN></A></LI>
      <LI><A href="#b"><SPAN>B</SPAN></A></LI>
      <LI><A href="#c"><SPAN>C</SPAN></A></LI>
      <LI><A href="#d"><SPAN>D</SPAN></A></LI>
      <LI><A href="#z"><SPAN>Z</SPAN></A></LI></UL></DIV>
      

      then I moved the list nav to the wiki page

      <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-latest.min.js"></script>
      <script type="text/javascript">
      $(".ms-wikicontent a").each(function(){
      
      	var thisHref = $(this).attr('href');
      	var index = thisHref.indexOf('#');
      	if(index>0){
      		$(this).attr('href',thisHref.substring(index));
      	}
      });
      
      </script>
      <style type="text/css">
      
      #myCustomMenu {
      /*float: left;
      width: 100%;		
      line-height: normal;
      border-bottom: 1px solid #666;
      margin-bottom: 1em; *//*margin between menu and rest of page*/
      /*overflow: hidden;*/
      /*
      position:relative;
      top:expression(this.offsetParent.scrollTop);
      */
      	}
      #myCustomMenu ul {
      margin: 0;
      padding: 8px 0 0 0;
      list-style: none;
      }
      #myCustomMenu li {
      display: inline;
      margin: 0;
      padding: 0;
      }
      #myCustomMenu a {
      float: left;
      background: url("/sites/globalmp/wikiTestLinks/left.png") no-repeat left top;
      margin: 0;
      padding: 0 0 0 6px;
      text-decoration: none;
      font:8pt verdana normal;
      }
      #myCustomMenu a span {
      float: left;
      display: block;
      background: url("/sites/globalmp/wikiTestLinks/right.png") no-repeat right top;
      padding: 6px 9px 4px 4px;
      /* margin-right: 2px; */
      color: #FFF;
      }
      
      /* Commented Backslash Hack hides rule from IE5-Mac */
      #myCustomMenu a span {
      float: none;
      }
      /* End IE5-Mac hack */
      #myCustomMenu a:hover span {
      }
      #myCustomMenu a:hover {
      background-position: 0% -42px;
      }
      #myCustomMenu a:hover span {
      background-position: 100% -42px;
      }
      .divPositionAbsolute {
       position: relative; 
      top: expression(this.offsetParent.scrollTop);
      	}
      
      </style>
      

      what I found was that the content needs to be wrapped in a div and I could only make it work placing it in a table reading from that same reference you mentioned.

      <style type="text/css">
      #myCustomMenu ul {
      margin: 0;
      padding: 8px 0 0 0;
      list-style: none;
      }
      #myCustomMenu li {
      display: inline;
      margin: 0;
      padding: 0;
      }
      #myCustomMenu a {
      float: left;
      background: url("/sites/globalmp/wikiTestLinks/left.png") no-repeat left top;
      margin: 0;
      padding: 0 0 0 6px;
      text-decoration: none;
      font:8pt verdana normal;
      }
      #myCustomMenu a span {
      float: left;
      display: block;
      background: url("/sites/globalmp/wikiTestLinks/right.png") no-repeat right top;
      padding: 6px 9px 4px 4px;
      /* margin-right: 2px; */
      color: #FFF;
      }
      
      /* Commented Backslash Hack hides rule from IE5-Mac */
      #myCustomMenu a span {
      float: none;
      }
      /* End IE5-Mac hack */
      #myCustomMenu a:hover span {
      }
      #myCustomMenu a:hover {
      background-position: 0% -42px;
      }
      #myCustomMenu a:hover span {
      background-position: 100% -42px;
      }
      
      .divPositionAbsolute {
       position: relative; 
      top: expression(this.offsetParent.scrollTop);
      	}
      </style>
      <DIV ><table><tr ><td>
      <DIV class=divPositionAbsolute id=myCustomMenu>
      <UL>
      <LI><A href="#a"><SPAN>A</SPAN></A></LI>
      <LI><A href="#b"><SPAN>B</SPAN></A></LI>
      <LI><A href="#c"><SPAN>C</SPAN></A></LI>
      <LI><A href="#z"><SPAN>Z</SPAN></A></LI></UL></DIV></td></tr>
      <tr><td>
      <DIV style="FONT: 8pt verdana;OVERFLOW: auto; HEIGHT: 420px">
      <P>Introduction</P>
      <P>Morbi congue interdum ultrices. Maecenas sed massa eu lectus dapibus suscipit. Fusce lorem elit, tristique sed ultrices ac, eleifend nec odio. Integer molestie, risus id commodo convallis, est massa convallis eros, nec scelerisque nisi nunc vitae odio. Quisque faucibus euismod eros, quis ultrices ante pulvinar vitae. Sed vitae ligula lorem, ac luctus odio. Fusce ac felis nec mi placerat cursus. Morbi luctus eleifend elit non faucibus. Duis egestas pharetra nulla, quis ullamcorper nisi accumsan vel. Nulla cursus malesuada nisi, id congue erat malesuada id. Pellentesque tempor est eu lacus porta ultrices. Sed suscipit porttitor nisi et ultricies. Morbi in libero id est iaculis vestibulum sed eget eros. Nullam rhoncus ante at neque iaculis et eleifend magna bibendum. Nunc varius semper urna, ut adipiscing massa fringilla pharetra. Quisque a lorem dictum nibh sodales elementum at quis libero. Donec lobortis nisi nec risus placerat auctor. Quisque sagittis magna a nunc eleifend id tempor nulla convallis. </P>
      <P><A name=a>A</A></P>
      <P>Morbi congue interdum ultrices. Maecenas sed massa eu lectus dapibus suscipit. Fusce lorem elit, tristique sed ultrices ac, eleifend nec odio. Integer molestie, risus id commodo convallis, est massa convallis eros, nec scelerisque nisi nunc vitae odio. Quisque faucibus euismod eros, quis ultrices ante pulvinar vitae. Sed vitae ligula lorem, ac luctus odio. Fusce ac felis nec mi placerat cursus. Morbi luctus eleifend elit non faucibus. Duis egestas pharetra nulla, quis ullamcorper nisi accumsan vel. Nulla cursus malesuada nisi, id congue erat malesuada id. Pellentesque tempor est eu lacus porta ultrices. Sed suscipit porttitor nisi et ultricies. Morbi in libero id est iaculis vestibulum sed eget eros. Nullam rhoncus ante at neque iaculis et eleifend magna bibendum. Nunc varius semper urna, ut adipiscing massa fringilla pharetra. Quisque a lorem dictum nibh sodales elementum at quis libero. Donec lobortis nisi nec risus placerat auctor. Quisque sagittis magna a nunc eleifend id tempor nulla convallis. </P>
      <P><A name=b>B</A></P>
      <P>Morbi congue interdum ultrices. Maecenas sed massa eu lectus dapibus suscipit. Fusce lorem elit, tristique sed ultrices ac, eleifend nec odio. Integer molestie, risus id commodo convallis, est massa convallis eros, nec scelerisque nisi nunc vitae odio. Quisque faucibus euismod eros, quis ultrices ante pulvinar vitae. Sed vitae ligula lorem, ac luctus odio. Fusce ac felis nec mi placerat cursus. Morbi luctus eleifend elit non faucibus. Duis egestas pharetra nulla, quis ullamcorper nisi accumsan vel. Nulla cursus malesuada nisi, id congue erat malesuada id. Pellentesque tempor est eu lacus porta ultrices. Sed suscipit porttitor nisi et ultricies. Morbi in libero id est iaculis vestibulum sed eget eros. Nullam rhoncus ante at neque iaculis et eleifend magna bibendum. Nunc varius semper urna, ut adipiscing massa fringilla pharetra. Quisque a lorem dictum nibh sodales elementum at quis libero. Donec lobortis nisi nec risus placerat auctor. Quisque sagittis magna a nunc eleifend id tempor nulla convallis. </P>
      <P><A name=c>C</A></P>
      <P>Morbi congue interdum ultrices. Maecenas sed massa eu lectus dapibus suscipit. Fusce lorem elit, tristique sed ultrices ac, eleifend nec odio. Integer molestie, risus id commodo convallis, est massa convallis eros, nec scelerisque nisi nunc vitae odio. Quisque faucibus euismod eros, quis ultrices ante pulvinar vitae. Sed vitae ligula lorem, ac luctus odio. Fusce ac felis nec mi placerat cursus. Morbi luctus eleifend elit non faucibus. Duis egestas pharetra nulla, quis ullamcorper nisi accumsan vel. Nulla cursus malesuada nisi, id congue erat malesuada id. Pellentesque tempor est eu lacus porta ultrices. Sed suscipit porttitor nisi et ultricies. Morbi in libero id est iaculis vestibulum sed eget eros. Nullam rhoncus ante at neque iaculis et eleifend magna bibendum. Nunc varius semper urna, ut adipiscing massa fringilla pharetra. Quisque a lorem dictum nibh sodales elementum at quis libero. Donec lobortis nisi nec risus placerat auctor. Quisque sagittis magna a nunc eleifend id tempor nulla convallis. </P>
      <P><A name=z>Z</A></P>
      <P>Morbi congue interdum ultrices. Maecenas sed massa eu lectus dapibus suscipit. Fusce lorem elit, tristique sed ultrices ac, eleifend nec odio. Integer molestie, risus id commodo convallis, est massa convallis eros, nec scelerisque nisi nunc vitae odio. Quisque faucibus euismod eros, quis ultrices ante pulvinar vitae. Sed vitae ligula lorem, ac luctus odio. Fusce ac felis nec mi placerat cursus. Morbi luctus eleifend elit non faucibus. Duis egestas pharetra nulla, quis ullamcorper nisi accumsan vel. Nulla cursus malesuada nisi, id congue erat malesuada id. Pellentesque tempor est eu lacus porta ultrices. Sed suscipit porttitor nisi et ultricies. Morbi in libero id est iaculis vestibulum sed eget eros. Nullam rhoncus ante at neque iaculis et eleifend magna bibendum. Nunc varius semper urna, ut adipiscing massa fringilla pharetra. Quisque a lorem dictum nibh sodales elementum at quis libero. Donec lobortis nisi nec risus placerat auctor. Quisque sagittis magna a nunc eleifend id tempor nulla convallis. </P></DIV></DIV>
      </td></tr></table>
      

      How can I make this work, frozen div head, scrolling text, without having to add a table?

    5. I know I am bothering the heck out of you with this. I almost have this complete. I just found this last issue and I dont like the way it is functioning. I have the top navigation which is an unordered list layout horizontally. My content is in a div with an OVERFLOW: auto; HEIGHT: 420px

      this allows the content to scroll up to the navigation tabs (bookmark links). in the wiki if I click a tab the entire page scrolls to the top right to the bookmark, hiding the tab navigation. I found this only happens when the SP page is already longer then what can be viewed on screen.

      1. how can I stop the entire page scrolling and only scroll the content of the div.

      2. I have a script to add/remove class on the tabs but only on hover. how can I add the same class when I click, but also remove that class when I click on another tab. Only want one tab with the class at a time like the hover function here:

       $(function(){
         $("#tabs li a").hover(function(){
           $(this).parents("li").addClass("selected");
         },function(){
           $(this).parents("li").removeClass("selected");
         });
         
       });
      

      when I add a click function I lose the hover. any suggestions?

    6. Hi,
      This is a bit to hard to piece together… If you could send me some sketches of what it is you want to happen, along with the code, i might be able to help.

      Alexander

    1. Hi,
      This is previously posted as answer to the same question:

      Add a CEWP below the list form in NewForm and EditForm. Insert this code:

      function PreSaveAction(){
        if(confirm("Are you sure?")){
          return true;
        }else{
          return false;
        }
      }
      

      SharePoint automatically executes any code in this function when pressing “OK”. It must return true for the save item to take place.

      Alexander

  144. Hi Alexander,

    is it possible to redirect new- and editform.aspx of a list to e.g. a webpart page? I’d like to set up a webpart page with cewp’s in the middle and on the side. The side webparts will be used to display additional information, the middle webpart(s) will be used for the new/editform.aspx

    Chris

    1. The default NewForm, DisForm and EditForm are defined on the list in SharePoint Designer. I think you could create a custom NewForm in SPD and use it, but i do not have any detailed walktrough on that as i newer modify the form other than using client side javascript…

      Alexander

  145. is it easy to have a popup window say from another list in SP. that a user can open scan the list click an item in the list and have it write that item to a field of a newform or the same or another list. It cant refresh the page or previously entered data could be lost.

    I have a location list broken out by country, 150 locations, 12 countries. I dont want to add addition additional fields (cascade). I though a popup win work a bit easier. when they get to this field they click to open the popup, find the location code, click the code and populate the field in the original newform.

    How hard is this to accomplish?

  146. Hi. I’ve been looking all over the internet for a clean way to simply query individual columns of data from a list.
    I would like to take a column and put all of the data into an array and then use that array elsewhere in my code (in a CEWP). So many blogs and posts seem to tell me what to do but I don’t think know enough about JQuery to understand exactly where the extracting of data is taking place. More importantly what jQuery libraries or functions would I need to use to perform such a function. I’m not looking for written code per se, I just am looking for a plain English explanation of what i would need to do.
    Thanks if you think you could help.

  147. Hi Alexander,
    I want to to be able to hoever over the name of file (Infopath) in form library and popup an image which is a hyperlink to picture in picture library and is related to the infopath form.

    Regards,
    Osama

  148. Using your init_fields_v2() to create a fields reference, how can I remove specific options from a SharePoint Select dropdown menu on one of my lists?

    1. Hi,

      This example removes the options Green and Yellow from the <select> with FieldInternalName “MySelect”.

      Add this code to a CEWP below the NewForm and/or EditForm:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      // Removes the options in the array "optToRemoveArr" from the select with FieldInternalName "MySelect"
      optToRemoveArr = ['Green','Yellow'];
      $(fields['MySelect']).find('option').each(function(){
      	var thisVal = $(this).val();	
      	if($.inArray(thisVal,optToRemoveArr)>-1){
      		$(this).remove();
      	}
      });
      
      
      /*
        LastMod: 07.05.2010
      */
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}		
      	});
      	return res;
      }
      </script>
      

      Modify the “src” to jQuery.

      Alexander

  149. Hi Alex,

    I’ve just got another question regarding this post

    https://spjsblog.com/2009/11/05/requests/comment-page-7/#comment-3340

    You’ve referred me to try

    <script type="text/javascript">
    var objDays = {'0':'Sunday','1':'Monday','2':'Tuesday','3':'Wednesday','4':'Thursday','5':'Friday','6':'Saturday'};
    // Get daynumber
    var dayNr = new Date().getDay();
    // Get friendly name
    var dayFriendly = objDays[dayNr];
    // Get path
    var partRaw = window.location.pathname;
    var path = partRaw.substring(0,partRaw.lastIndexOf('/')+1);
    // Redirect if href do not contain "StopRedirect" - add this if you do want to stop the redirect: .../AllItems.aspx?StopRedirect
    if(window.location.href.indexOf('StopRedirect')<0){
    	window.location.href=path + dayFriendly + ".aspx";
    }
    </script>
    

    Unfortunately I’m not enough of a programmer to make this work with calendar weeks. From what I’ve made up so far (theoretically) I have to create 52 columns representing the weeks for a year. Then I have to create views that show 4 weeks, starting from cw01-04 and so on.

    My problem starts with the calculation of the correct week for this ‘autochanger’ and continues to the part where my columns should show the reporting date instead of a calendar week, e.g. 01.01. 08.01. 15.01. and so on, increasing by 7 days.

    I might be able to change that to a calendar week naming, however I’d still have a problem in the new/editforms since I don’t want to display 52 items all the time when only one is necessary (the current week item).

    Can you nudge me into the right direction regarding a calendar week calculation for the sript above?

    thanks,
    Chris

    1. Hi,
      I’m a bit confused. I have read your original request and then this one. I must admit i do not quite understand what you want to achieve.

      What kind of information is supposed to go into these 52 columns?

      Please e-mail me some sketches or some more details and i might be able to help.

      Alexander

  150. Hello Alex,

    I would like to ask you for some help, as i am trying to make a field update mechanism on the dispform.aspx. For example, when i open a sharepoint item and see the display form to have a button and when clicked to update the same item on a specific choice field only, in a way to manipulate it, from Status In Progress to be able to set it to Completed or something like that.

    Regards,
    Esad

    1. Something like this Get or Set value for SharePoint field in NewForm, EditForm and DispForm (Get only in DispForm), just to be able from a buton on the DispForm to update a hidden/non-visible field.

  151. Hey Alex, another question for you:
    How would one, using your init_fields_v2() function, set a multiple lines of text control to be disabled and change the width of it?

    I’ve been toying with it for some time now and decided to turn to the master for assistance. 🙂

    Thanks!

  152. I have seen some fo the script where you can hide list view menu and hide individual items (views). Is there a way to dynamically change the label. I am creating some views like, Current Year, Last ayear, Current Month and Last Month.I would like to replace the text with the current date.

    Current Year = “Year – 2010”, but next year it reads “Year – 2011”
    same for month
    Current Month = “July – 2010”, but next month reads “August – 2010”

    can this be done?

  153. Hi,

    The people I’m working for have a request to basically “google” search a very large list (800+ objects). They want to be able to enter in a few keywords into a search box and have a filtered list returned. They don’t care which column the term falls in, it should all be found in the search.

    I’ve currently implemented this idea using Javascript, but it has some limitations. First, it can only search the entire list if the entire list is visible to begin with. With 800+ items and IE6 requirement, this is bad. 2nd, it’s pretty darn slow on IE6 which is what I’m stuck with using.

    My knowledge of JQuery is pretty limited so I’d be very thankful if there was a faster better solution than what I currently have.

    [sourcecode language="Javascript"]

    Search: <input id=tSearch class="ms-long" type="text" onkeyDown="return entsub(this.value, event)" />
    <INPUT id=btnSearch onclick="return filterWords(document.getElementById(‘tSearch’).value);" value=Search type=button>
    &nbsp;
    <INPUT id=btnClear onclick="return clearPage();" value="Clear Quick Search Results" type=button>
    <INPUT id=btnClear onclick="return resetPage();" value="Clear All Search Results" type=button><br>
    <b>Results: <div id=results></div>

    <script type="text/javascript">

    var lvRows = null;

    /*** gets the list table from the page source code ***/

    function getElementsByCssClass(sTagName, sClassName) {
    var results = new Array();
    var allTagElements = document.getElementsByTagName(sTagName);
    for (i = 0; i < allTagElements.length; i++) {
    var className=allTagElements[i].className;
    if(className.match(sClassName)) results.push(allTagElements[i]);
    }
    return results;
    }

    /*** removes rows that do not contain the given search term ***/

    function quickSearch(terms, lvRow, count) {

    for(i = 0; i < terms.length; i++) {

    if(lvRow.style.display != ‘none’){
    if(getTxt(lvRow).toLowerCase().indexOf(terms[i].toLowerCase()) > -1) {
    lvRow.style.display = "block";
    }
    else {
    //if term is not found in row, row becomes not visible
    lvRow.style.display = ‘none’;
    count–;
    }
    }
    }
    return count;

    }

    /*** Makes all rows in the list visible ***/

    function makeVisible(lvRows) {
    for(i = 1; i < lvRows.length; i++) {
    lvRows[i].style.display = "block";
    }
    document.getElementById("results").innerHTML = lvRows.length-1;
    }

    /*** gets the text from the fiven object ***/

    function getTxt(obj) {
    if(obj.innerText) return obj.innerText;
    else return obj.textContent;
    }

    /*** Filters multiword entry with spaces as the delimiter ***/

    function filterWords(input) {

    var wordList = new Array();
    var searchTerm = "*";
    var count = 0;
    var searchWord = "";

    // Iterates over every character, adding new words to Array
    while(count <= input.length-1){

    // " " is ignored and all previous text is added to Array
    if(input.charAt(count) == " "){
    searchTerm += searchWord;
    searchTerm += "*+*";
    wordList.push(searchWord);
    searchWord = "";

    }
    else{
    searchWord += input.charAt(count);
    }
    count++;
    }
    searchTerm += searchWord;
    wordList.push(searchWord);

    //reset table to full for each new search
    if(lvRows == null){
    var lvTable = getElementsByCssClass("table","ms-listviewtable")[0];
    lvRows = lvTable.childNodes[0].childNodes;
    var add = 1;
    }
    makeVisible(lvRows);
    var counter = lvRows.length-1;

    // for each word in search, filter
    for(var i = 1; i < lvRows.length; i++){

    if(lvRows[i].style.display != ‘none’){
    counter = quickSearch(wordList, lvRows[i], counter);
    }
    }
    document.getElementById("results").innerHTML = counter;
    }

    /*** Ensures enter must be pressed before search commences ***/

    function entsub(myfield,e) {
    var keycode;
    if (window.event)
    keycode = window.event.keyCode;
    else if (e)
    keycode = e.which;
    else
    return true;

    if (keycode == 13) {
    filterWords(myfield);
    return false;
    }
    else
    return true;
    }

    /*** resets page filter search completely ***/

    function clearPage() {
    if(lvRows == null){
    var lvTable = getElementsByCssClass("table","ms-listviewtable")[0];
    lvRows = lvTable.childNodes[0].childNodes;
    }
    makeVisible(lvRows);
    }

    /*** Hard refreshes original page to remove all extra filtering that may have taken place ***/

    function resetPage() {

    var refreshURL = "";
    var input = window.location.toString();
    var count = 0;
    while(count <= input.length-1){

    // " " is ignored and all previous text is added to Array
    if(input.charAt(count) == "?"){
    window.location.href = refreshURL;
    return true;
    }
    else{
    refreshURL += input.charAt(count);
    }
    count++;
    }

    window.location.href = refreshURL;
    }

    </script>
    <script>window.tt_HideSrcTags.done=true;</script>

    1. Hi,
      To use javascript/jQuery against a standard list view, all rows must be visible.

      To overcome this you would have to make a custom query using a ajax webservice call, and parse the returned XML, reformatting it in a HTML table style.

      This is absolutely manageable, but I do not have the time to help you with this at the moment.

      Alexander

  154. Hi Alex:
    On a SP List, is it possible with Jquery to transpose the rows and columns so that the column headers become the row headers, and the row items are listed across the column headers?

    Thanks-

    Charlie

    1. (had to put this into the corrrect Reply zone)
      Hi Alex:
      In the simplest terms,

      ________Item #1 Item #2 Item #3 Item #4
      Field 1
      Field 2
      Field 3
      Field 4

      Thanks-

  155. Hey A,

    Do you have a post in here related to make a field required based on a selection from another field? I cant recall if you worked this

  156. I have another new request. this one more important than the previous, making field required based on user selection.

    I have been trying to create a copy text script, that allows me to copy data from a column.

    I have a title field (singleline), CSS (multipleline), CC.
    the title just contains the tile of the item and is unique.
    CSS contains actual css like this:
    [sourcecode]
    .ms-globalbreadcrumb {
    font-size:8pt;
    text-align:right;
    background-color:#ebf3ff;
    padding:2px 10px 2px 5px;
    }

    I want to click something (button, link, maybe even the text) and it copy the text to the clipboard.

    because the title is unique I can create an ID using this field in my CC like this:

    ="<span id='"&[Title]&"'>"&[CSS]&"</span>"
    

    then I added one last CC to add my button:

    ="<input type='button' value=Copy' onclick='ClipBoard('"&CSS&"');' />"
    

    With ‘ClipBoard as my copy function

    <script type="text/javascript">
    function ClipBoard(Container) {
    	var obj=document.getElementById(Container);
    	holdtext.innerText = obj.innerText;
    	Copied = holdtext.createTextRange();
    	Copied.execCommand("Copy");
    }
    </script> 
    

    I use Christophe’s Script HTMLcc to transpose the HTML.

    No matter how I try this I can not get the function to work.

    Is there a way to add a function to copy text (Code or CSS) from another column or field in a list view?

    1. I had entered my button text wromg, this is what I actually have and it doesn’t work

      ="<input type='button' value=Copy' onclick='ClipBoard('"&[Title]&"');' />"
      
  157. Hello Alex,

    Thank you for a wonderful site – I have enjoyed using a number of your solutions. I have what I think is a very simple question that I have yet to find a solution for, and am wondering if you could offer a suggestion. Is there a good method to change the ms-formlabel related to “Content Type” on editform.aspx? I am using Content Types to control the status of tasks as they move through a process and would like to make it more clear for my users. Any help you can ofer is greatly appreciated!

    Thanks, Isaac

    1. Thanks Alex, sorry for this late reply. I finally had a chance to look at the post you referenced, and can see where you are identifying the content type drop down in your function for hiding the field. I’ve taken a crack at it, but am not getting the result i am looking for – I imagine my syntax is probably very incorrect. Could you take a look at my mangled code?

      <script type="text/javascript">
      
      {
      $("select[id$='ContentTypeChoice']").innerHTML="Review Status";
      }
      
      </script>
      

      I have also tried this variation based on another method for changing a field label I saw elsewhere:

      <script type="text/javascript">
      
      {
      document.getElementById("ContentTypeChoice").innerHTML="Review Status";
      }
      
      </script>
      

      Each variation I have tried has either resulted in no change or an error message (“unexepected error occurred”). Thanks for your help, any advice is appreciated!

    2. Hi,
      Like this for EditForm:

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script type="text/javascript">
      $("select[id$='ContentTypeChoice']").parents('tr:first').find('td.ms-formlabel').text('Review status');
      </script>
      

      And this for DispForm:

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
      <script type="text/javascript">
      var contentType = $("span[id$='InitContentType']").text();
      var newRowBuffer = [];
      	newRowBuffer.push("<tr>");
      	newRowBuffer.push("<TD class=ms-formlabel vAlign=top width=165 noWrap>");
      	newRowBuffer.push("<H3 class=ms-standardheader>Review status</H3>");
      	newRowBuffer.push("</TD>");
      	newRowBuffer.push("<TD id=SPFieldText class=ms-formbody vAlign=top width=450>"+contentType+"</TD>");
      	newRowBuffer.push("</tr>");
      	newRow = newRowBuffer.join('');
      $('table.ms-formtable tbody').prepend(newRow); 
      </script>
      

      Alexander

    3. That is fantastic, I can’t thank you enough! From looking at your code I can also see where I was going wrong. Your site is, as ever, a wonderful resource!

      Thanks again,
      Isaac

  158. Hi Alex:
    Is it possible to grab the group totals from the .ms-alternating line up to the .ms-gb line? And to move up the same info for a sub-group.

    The purpose is so the data can be viewed in collapsed mode and still be able to see the totals for each group or sub-group.

    Thanks-

    Charlie Epes

    1. Hi,
      I’m not sure if this would work if the groups are initially collapsed. The data is not rendered before the group is expanded, and therefore i do not think this will be possible.

      Alexander

    2. Hi,
      I did a quick test and found that id does render (hidden, but renders). I’m not quite sure how you want this to look like so please give me a sketch of how you would have the setup and i can take a look at it.

      Alexander

    3. Try this one – Note: The groups must be expanded by default

      <script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      $(document).ready(function(){
      	$("tbody[id^='aggr1-']").each(function(){
      		if($(this).prev().find('td.ms-gb').length==0){		
      			$(this).prev().find('td:first a:last').click();
      			thisSum = $(this).find('tr:first td:first').nextAll().addClass('ms-gb2').append('&nbsp;');
      			$(this).prev().find('td:last').attr('colspan',1).after(thisSum);			
      		}
      	});
      });
      </script>
      

      Alexander

  159. i am trying to search the items in a custom list in sharepoint201 using below
    code

    
    <script type="text/javascript">
    function RedirectUrl() {
    var tb = document.getElementById("tbSearch").value;
    var cs = document.getElementById("sfield").value;
    var url = "";
    if (tb != "") {
    url = "FilterName=" + cs + "&FilterMultiValue=*" + tb + "*";
    window.location.href = "Read List.aspx?" + url;
    }
    else {
    return false;
    }
    }
    function ClearUrl() {
    window.location.href = "Read List.aspx";
    }</script>Search Field: <select id="sfield"> <option value="ID">InstanceID</option>
    
    <option value="Name">InstanceFullName</option>
    
    <option value="Column3">InstanceDescription</option>
    
    <option value="Column4">InstancePOC</option>
    
    <option value="Column5">InstanceTierID</option>
    
    <option value="Column6">InstanceCreateDateTime</option>
    
    <option value="Column7">CreateDateTime</option>
    
    <option value="Column8">ModifiedDateTime</option>
    
    <option value="Column9">BusinessUnitID</option>
    
    <option value="Column10">IsClustered</option>
    
    <option value="Column11">IsSOXCompliant</option>
    
    <option value="Column12">instanceBackupPath</option>
    
    <option value="Column13">DefaultDatabaseApplicationID</option></select>
    
      Search text: <input id="tbSearch" type="text"/>
    
    <input id="btnSearch" onclick="return RedirectUrl();"
    
    type="button" value="Search"/>
    
    <input id="btnClear" onclick="return ClearUrl();" type="button" value="Clear"/>
    

    but it doesn`t work?
    can you please help in achieving it

    Thanks in Advance

    1. Hi,
      Try changing “FilterName” and “FilterMultiValue” with “FilterField1” and “FilterValue1”. Remove the * wrapping the query string.

      Alexander

  160. Hi Alex:
    Forgive me if I’ve asked this before.

    I would love to find a way to use the best features of a Document Library (metadata) combined with a Custom List.

    The attachment feature in a List is not sufficient as the library docs are stored in a relatively hidden and inaccessible file.

    Do you have any ideas?

    1. Hi,
      What is stopping you from using metadata on the document itself?

      I do not have any other feasible method for creating this “relationship” other than SharePoint’s lookup columns.

      Alexander

  161. Good Day A,
    I need some help with jquery. I have several checkboxes setup where if you check it some text displays. fairly simple function like this:

    <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-latest.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
    	$('#Course1Selected').click(function() {
        	$("#course1Link").toggle(this.checked);
       	});
    	$('#Course2Selected').click(function() {
        	$("#course2Link").toggle(this.checked);
       	});
    	$('#Course3Selected').click(function() {
        	$("#course3Link").toggle(this.checked);
      	});
    });
    </script>
    
    <label for="checkbox">Check If you're a member of:</label><br />
    <input type="checkbox" id="Course1Selected" />Sect 1
    <span id="course1Link" style="display: none">Link to <a href="#">Course 1</a></span><br />
    <input type="checkbox" id="Course2Selected" />Sect 2
    <span id="course2Link" style="display: none">Link to <a href="#">Course 2</a></span><br />
    <input type="checkbox" id="Course3Selected" />Sect 3
    <span id="course3Link" style="display: none">Link to <a href="#">Course 3 </a></span>
    

    This works well, but what I want to do is only show one link (area) at a time no matter how many checkboxes are selected. The area I want to show is the one closest to the top (in order) or the lowest number.

    Example: If I check Sect 2 and Sect 3 only the area for Sect 2 displays.
    If I select Sect 1 and Sect 3 then only the area for sect 1 displays. Also if only one is selected then that one displays.

    can this be done?

    1. Hi,
      You would have to add a function to loop trough all the “containers”, checking if they are visible or not. Then based on your logic, decide whether to expand it or to leave it collapsed.

      You would have to call this function rather than to toggle the container directly.

      Hope this helps you on the way.

      Alexander

    2. Hey A, I know your busy and hate to bother you. I’m stuck on this. My skills are not good enough to figure out how to write this function to loop through.

      Can you get me started? I think once I have some with an idea i can figure it out.

    3. Here is a possible answer:

      <div id='checkBoxWrapper'>
      	<label for="checkbox">Check If you're a member of:</label><br />
      	<input type="checkbox" id="Course1Selected" />Sect 1
      	<span id="course1Link" style="display: none">Link to <a href="#">Course 1</a></span><br />
      	<input type="checkbox" id="Course2Selected" />Sect 2
      	<span id="course2Link" style="display: none">Link to <a href="#">Course 2</a></span><br />
      	<input type="checkbox" id="Course3Selected" />Sect 3
      	<span id="course3Link" style="display: none">Link to <a href="#">Course 3 </a></span>
      </div>
      
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
      <script type="text/javascript">
      $(document).ready(function(){
      
      	$('#Course1Selected').click(function() {
      		showCourseLink();
         	});
      	$('#Course2Selected').click(function() {
      		showCourseLink();
         	});
      	$('#Course3Selected').click(function() {
      		showCourseLink();
        	});
      });
      
      function showCourseLink(){
      	// Hide all
      	$("#checkBoxWrapper span").hide();
      	// Unhide the topmost
      	$("#checkBoxWrapper").find('input:checkbox').each(function(){
      		var checked = $(this).attr('checked');
      		if(checked){
      			$(this).next().show();
      			// Exit loop
      			return false;
      		}
      	});
      }
      </script>
      

      Alexander

    4. that is perfect. So I have been playing with adding some formatting. each time I add something I lose the function. Initially had it setup in a table where I was trying to hide the last cell to the right. I removed the table and just added span tags, P tags just around the check box like this:

      <span class="label"><input type="checkbox" id="CourseSelected1" /> Health Care Vertical (HCV) </span>
      <span class="text" id="courseLink1" style="display: none">
      Link 1 <a href=#">course 1</a></span>
      

      even like this

      <input type="checkbox" id="CourseSelected1" /> <span class="label">Health Care Vertical (HCV) </span>
      <span class="text" id="courseLink1" style="display: none">
      Link 1 <a href=#">course 1</a></span>
      

      Still lose the function.
      I know by adding the span around the input it changes its location in the node tree, but what about the label?. I’m just not sure how to identify it. I have tried several things, but like usual just cant hit the right one.

      otherwise this works perfect, as requested.

    5. never mind. thank again for all your time. I was able to figure it out to trigger the function again and added the content into a table.

      thanks a million

  162. Quick question I am able to show/hide fields based on selection in a survey using your script but unable to hide the msformlabels. It normally works fine but it is not working on a survey?

  163. Hi Alex, been a while, sorry that I haven’t send anything on the ‘rotating columns’ yet, it’s been quite busy here lately. Nevertheless, I can’t get my hands off of sharepoint, the challenge I’m currently trying to solve is to get the attachments paperclip in a listview clickable. Using a doclib and linking against the file is not an option since we are talking about a lot of files with the same name which should be stored with the list entry (one file per entry).

    There’s a solution from Paul Grenier at EUSP, http://www.endusersharepoint.com/2009/02/12/jquery-for-everyone-linking-the-attachment-icon/ but that doesn’t work for large collections, so it’s not usable.

    I thought of setting up the path ‘manually’, and displaying this entry, since I noticed that the attachment path is always like URL/site/lists/listname/attachments/list_item_id/filename. Though I might be able to come up with all the details up to the ID I have no idea on how to get the filename automatically.

    Can you think of any other way to make the paperclip clickable to open the attachment?

    Thanks,
    Chris

  164. Hi Alexander,
    I’m working with SharePoint 2007 and am trying to modify a list edit form. The result/outcome I’m trying to achieve is:

    – Hide and/or replace the default ok and cancel buttons with my own options – approve, save, cancel.
    – My buttons would update the value of a hidden status dropdown field on the form to a desired value (for use by a workflow).

    I’ve tried to accomplish this using the action button within sharepoint designer, but have not had success. It seems as though this should be possible with some clever javascript – though I’ve been unsuccessful so far.

    Any guidance is appreciated!

    Travis

    1. Hi Travis,

      for a start, to replace the default texts within the form buttons you can use this code.

      <script type="text/javascript"></script>
      <script>$("input[id$='SaveItem']").val('Save');
      </script>
      

      This will change the “OK” to “Save”. For “Cancel” I think the id$ has to be “GoBack”. I can’t help you with adding a third button though and for changing the value of a field I’m rather clueless too, maybe have a search for presave options to get more info on this topic.

      Chris

    2. Travis, here is some code to add a button to the edit form. Currently I am using this to add a Help button which launches a popup window with help information. Using Chris information, or search with in here A also has a script, you could rename your buttons. then you can add this script into a CEWP to get your third button.

      <style>
      .ButtonHeightWidth {
      width:7.5em;
      font:8pt tahoma;
      height:2.1em;
      padding-top:0.1em;
      padding-bottom:0.4em;
       border: none;
         background-color:#3399FF;
         filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0,StartColorStr='#ffFFFFFF',EndColorStr='#ff3399FF');
      
      }
      
      
      </style>
      <table style="display:none">
      <tr>
      <td id="oCustomButton" class="ms-toolbar" nowrap="true"> 
      <table cellpadding="0" cellspacing="0" width="100%">
      <tr>
      <td align="right" width="100%" nowrap><input type="button" value="Help ?" 
      onclick="window.open('/sites/learning/LMS/LOPS/Lists/PDC-LMSSupportRequests/Help.aspx','mywindow','width=800,height=675,top=50,left=50')" class="ms-ButtonHeightWidth" />
      </td>
      </tr>
      </table> 
      </td>
      <td id="oSeparator" > <img src='/sites/cmgtraining/ops/pmo/images/spacer.gif' border=0 width=5/> </td>
      </tr>
      </table>
      
      <script language="javascript" type="text/javascript">
      _spBodyOnLoadFunctionNames.push("attachCustomButton"); 
      
      function attachCustomButton()
      { var oAryTables = new Array();
      var oCustomButton = null;
      var oSeparator = null;
      var oNodeTemp = null;
      oCustomButton = document.getElementById("oCustomButton");
      oSeparator = document.getElementById("oSeparator");
      oAryTables = document.getElementsByTagName("table");
      for(var i = 0; i < oAryTables.length; i++)
      { if(oAryTables[i].className == "ms-formtoolbar")
      { oNodeTemp = 
      oAryTables[i].firstChild.firstChild.insertBefore(oSeparator.cloneNode(true), 
      oAryTables[i].firstChild.firstChild.firstChild.nextSibling); 
      oAryTables[i].firstChild.firstChild.insertBefore(oCustomButton.cloneNode(true), 
      oNodeTemp); 
      } 
      } 
      } 
      
      
      </script> 
      
    3. Hi,
      Here is another method of getting a third button (or more):

      <script type="text/javascript" src="../../Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      var buttonBuffer = [];
      	buttonBuffer.push("<td width='100%' align='right' noWrap='nowrap'>");
      	buttonBuffer.push("<input class='ms-ButtonHeightWidth' type='button' value='My new btn' onclick='javascript:MyButtonClick();return false;' />");
      	buttonBuffer.push("</td>");
      	buttonBuffer.push("<td class='ms-separator'>&nbsp;</td>");
      	newButtons = buttonBuffer.join('');
      
      // Find the input with an id ending with SaveItem. This is the "OK" buttons, Go one step up, to the <TD>, and insert the HTML buildt above before the "OK" button
      $("input[id$='SaveItem']").parent().before(newButtons);
      
      function MyButtonClick(){
      	alert("Clicked!");
      }
      </script>
      

      To interrupt the save process, use the “PreSaveAction()”. This function is automatically executed between the click of the “OK” button and the actual save.

      function PreSaveAction(){
      	if(confirm("Do you want to save this item?")){
      		return true;
      	}
      }
      

      Note that this function must return true for the save to happen.

      Alexander

  165. Alexander,

    Have you created a script that forces users to click the drop down on the new button in a document library? This way you can force users to pick the appropriate content type, rather than having a user click the new button, which loads the default content type?

  166. Alexander – thanks for taking open requests. I have been trying to create iGoogle style page, see this URL http://nettuts.s3.amazonaws.com/127_iNETTUTS/demo/index.html to get an idea of what I mean. The user can at browser level move the widgets to any section on the scree. I was wanting the same functionality but wrapped withing SP 2007 web parts. Is this possible? If yes, can it also store the user settings in cookies? I am trying to use the Personlization Site of SP 2007 to achieve this.

    thanks in advance.

  167. Hi Alexander,

    I’m working with a Lookup field in a listview and I would like to change the default behaviour of the “close” button to return to the original list instead of the “lookup list”.

    I think this can be done by adding a “&source” parameter to the close button I have no idea how this can be done. Can you help?

    Chris

    1. Hi,
      The source must be in the URL when you load the form. If not, you must change the “action” attribute for the aspNetForm and add i there. In any case, you must have the URL you want to return to… Maybe the best method is to add some jQuery to your list view to insert the “Source” in the url?

      One other method is to edit the close button behavior to go back one step (like hitting the back button in the browser).

      Alexander

  168. Oh, and I’ve got another wish. I’ve successfully implemented the Chart API with some pie charts. Now I’d like to display a sum of all the entries that a pie is created from. The google api doesn’t offer such a parameter. Is there any way to have like a heading for the pie’s that will count all items that the pie has been created of? Like a back-link to the view or something?

    Chris

  169. Am creating a SharePoint script library for various site owners within my organization to leverage (via a CEWP > Content Link).

    This has worked very well for simple scripts that require no user customization – i.e. Christophe’s EasyTabs, Quick Launch toggles, etc.

    The only “customizable” scripts we have are your Chart using Google Visualizations API based scripts. I created multiple configurations of charts from a single chart to a 3×3 table, using different div id’s as you suggest, and all is outstanding.

    Is there a simple template you have to use this type of customization for other scripts – I have meandered through your js, and my head beings to spin (I am NOT js literate, but can manage to edit basic scripts to serve my purpose in most cases).

    A few examples of scripts with universal value, but require some ability to customize are:
    Scrolling text marquees (edit width, speed, text, etc)- I would think this to be a simple one
    Customizing column widths in a List’Display (column name, width) – I would think this harder

    Can you post or produce a template of the key parts to have a script:
    – identify that no config list exists, and create as needed
    – how to build the screen to allow the fields to be written to the config list
    – how to pull them back into the script

    I do not think I have a need to read data from a list (like the charts you have amazingly developed) with the exception of reading back the user created config values.

    I can send a script or two (the ones re: above) if that helps!

    Thanks for any guidance, and all that you have produced so far!

    1. Hi,
      I like the idea, but have little time at the moment and cannot promise anything. It sure sounds like a good idea though.. I will keep it in mind an maybe follow up on it when things calm down a bit.

      Alexander

  170. Alexander,

    I am having problems displaying a week events view for a calendar information because of reoccurring meetings.

    Would it be possible for you to create a jquery filter that could be used in a CEWP for the calendar current events view that would filter everything by a between specific dates?

    I tried using the code listed here http://social.msdn.microsoft.com/Forums/en-US/sharepointcustomization/thread/d7be2bea-bab9-43a8-a7f6-b934f3b529bf but it did not work correctly for me.

    thanks!

  171. Hi,

    I am using sharepoint Offic Designer 2007, to validate a checkbox(terms and conditions) thru javacsript.

    Details:

    I have created a custom list and in the custom there is a field called terms and conditions. I have inserted the custom list in custom.aspx page. I have changed the sharepoint checkbox to asp checkbox for validation purpose.

    And I am trying to validate it through client validation function by aspx custom validator. My code looks like

    function TermsValidate(sender, args)

    {

    args.Isvalid=documnent.getelementById(“ff2_1”).checked);

    }

    The validation looks like it is triggering but object required error comes up. Because “ff2_1” is a sharepoint control and it is not able to recognize the control field..

    Does any one faced or come across this problem?

    If you have validated sharepoint controls with javascript without changing them to apsx controls. I am keen to take that approach.

    My requirement is I have to validate the checkbox field.

    Thank you

    1. Add this code in a CEWP below the unmodified SharePoint Form (NewForm.aspx or EditForm.aspx):

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      function PreSaveAction(){
      	var checked = $(fields['MyBoolColumn']).find('input:checkbox').attr('checked');
      	if(!checked){
      		alert("You must accept the terms!");
      		return false;
      	}
      	return true;
      }
      
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      </script>
      

      Read her how to add a CEWP to a SharePoint form page

      NOTE: You must change the FieldInternalName “MyBoolColumn” in the function “PreSaveAction” to match your field.

      Alexander

  172. I would like to be able to resize the column header height (in Datasheet view). Currently, it only allows to resize the width. Is there any script I can use to do this? Thanks!

    1. There are several methods to achieve this. I am going to post the 2 solutions. One from A that I believe works the best and another one I have pieced together.

      Instead of using a number field you can use single line of text. the script below will only allow numbers to be entered into the field. It is treated as text in SharePoint and you cannot sum or average in a list view. Add Below NewForm or EditForm

      <script type="text/javascript" src="/site/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      // Allow numbers only in text fields
      // Array of FieldInternalNames to lilmit to numbers only
      var arrToCheckForNum = ['Title','Num'];
      // Array of length of input string - set to 255 if you do not want to limit input length. Corresponds to the same array index in the "arrToCheckForNum"
      var lengthOfInputNumber = [9,2];
      
      $.each(arrToCheckForNum,function(idx,item){
      $(fields[item]).find('input').css({'width':'75px'});
      	$(fields[item]).find('input').keyup(function(e){
      		var thisVal = $(this).val();
      		thisVal = thisVal.substring(0,lengthOfInputNumber[idx]);
      		$(this).val(thisVal.replace(/[^0-9]/g,''));
      	}).blur(function(){
      		var thisVal = $(this).val();
      		thisVal = thisVal.substring(0,lengthOfInputNumber[idx]);
      		$(this).val(thisVal.replace(/[^0-9]/g,''));
      	});
      });
      
      /*
        LastMod: 07.05.2010
      */
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      </script>
      

      To go the other route I have found placing a script on the list view removes the commas and returns a number. Add below the List view

      <script type="text/javascript" src="/site/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      $("td[class='ms-vb2'] > div").each(function() {
      	var inner = $(this).html();
      	$(this).html(inner.replace(/[^0-9]/g,''));
      });
      </script>
      
  173. I am looking to find a way to autopopulate a user’s manager name or account name to a field on newform.aspx. The information is in AD, we do have MOSS, and I know I can do it using a custom form and the current user filter web part. However, I’m trying not to use a custom form. Is there any way to pull this info? The manager’s name is visible from the My Site Details page, but not from the {servername}/_layouts/userdisp.aspx. I am already using Javascript to pull the other fields I need, manager is the only one I haven’t been able to get yet. Any ideas?

    1. When using MOSS you have a webservice named “userprofileservice.asmx” that will “give” you this info.

      Let me know if you need any help.

      Alexander

  174. I would like to create a New Form page which has a employee ID. When user enters employee ID, then the rest of the fields (like department, work phone, etc..) should populate, getting information from Active Directory. Is there a solution for this using jQuery. Thanks!

  175. I Have a two columns in a list

    one is status(drop down)-(open, hold, pending verification)
    other is status Description(multiline textbox).

    can you help with javascript that validates two columns

    I want Status Description to be required field, if status is not equal to open.

    thanks in advance!

  176. Sure,

    You can do that using simple javascript. Open the form in SPdesigner Window.

    Try to use the jquery and it can be done.

    Need More help let me know. I will show you how to do that.

    Hari

  177. Hi SPKID

    You can do that using simple javascript. Open the form in SPdesigner Window.

    Try to use the jquery and it can be done.

    Need More help let me know. I will show you how to do that.

    Hari

    1. google.load(“jquery”, “1.4.2”);
      google.setOnLoadCallback(function()
      {

      $(‘#your control id’).change(function()
      {
      if(condition )
      {
      your code;
      }
      else
      {

      your code
      }
      );

      });

  178. G’day Alexander, Love your work. You provide some excellent solutions.

    I’ve got your SP Hit Counter functioning great on my Intranet work site.
    https://spjsblog.com/2010/02/18/hit-counter-for-sharepoint/

    My question is: For a generic SP Blog site, is there a way to count individual Blog Post hits? And have this counter displayed on each Post?

    Not the posts that are default on the front screen but when the user clicks on each post within each category. ie: ../Blog/Lists/Posts?id=1

    Your JQuery Hit Counter solution only works as a CEWP which would count every time the Posts.aspx page is loaded.

    The solution I require is for the users to know the popularity of each Post. And I think a Counter would be the soultion.

    Can this be done via a Calculated Column in each Blog? Or using DVWP for the HitCounter List? Or if you know of a better/easier solution, please let me know.

    Thanks,

    Brett.

  179. Hi, Alexander.
    First of all – many thanks for your work and help here, so many interesting things you’re doing! This is great!!
    I’m very interested to get a specific data in SP list – I mean data from external SQL table. As I’ve discovered in the Internet – it’s possible but so hardly ( for me especially 🙂 ) and many people said that it has many risks to connect to SQL DB from jscript because of security issues, etc. But in my case I have read-only access credentials to DB and want to get the data into list field from a table.
    In my case I have many data about users in SQL DB and I want to use paste that data into SP list, so I could bring much power to lists ( or other SP elements ).

    So, how hard is it – to tie together SQL queries and jscript ( for SP )??

    Thank you very much in advance!!

  180. Greetings Alexander,

    Got another challenge or humble request for you.
    Topic: SharePoint Survey/Poll

    Can JQuery be used for a single question Poll in a Web-Part?
    So that when a User answers the question, it then displays a Results Web-Part, perhaps a Bar-Graph?

    I can get the Poll into a web-part using this: http://www.endusersharepoint.com/2010/04/22/create-a-polling-web-part-with-sharepoint-designer-and-the-dvwp/
    But no Results can be displayed after the user Votes.

    I tried using this to display the Results but this will not show the Summary.ASPX of the Survey:
    http://www.pathtosharepoint.com/sharepoint-user-toolkit/Pages/Cross-Site-List-Snapshot.aspx

    Is there a way to do this via a Custom List?

    Thanks,

    Brett

    1. Hi,
      I will take the challenge 🙂 I will post a poll solution that support multiple simultaneous polls – with graphical summary. Keep looking for it during next week.

      Alexander

  181. Hi Alexander.

    i try to fill fileds with values in the Newform.aspx from a Customers list. Better, i have a lookup field to a customers List, i want dynamicly get the Values from this selected Customer and write them to fileds in my Newform.aspx. So i can make changes to these values. That changes where only saved in the new created item, not in the Customers list.

    Is this possible?

    Regadrs, Maik

  182. Hi Alex,

    i have another request or better question. I have a webpart on a Newform.aspx page. Here i can add a new item to a list. On my Newform.aspx is a lookup column to that list. How can i update that lookup column on that page when a new item is added to that list? When adding an item to that list thru the webpart, i make refesh that Newform.aspx.
    Also how can i save value in fields on the Newform.aspx when refreshing that page.

    Regards Maik

    1. Hi,
      I do not think you can add another item to a lookup without refreshing the form. It might be possible “hacking” into the javascript that is used to populate the original control, but i have no code examples available.

      Saving items in newform is not possible without using some code to preserve the values and refill the form when refreshed.

      Alexander

  183. Hi

    Apologies if this has already been asked but how how can I format Multi-select column results in DispForm?

    Instead of seeing something like this:

    value1;value2;value3

    it will be

    value1 | value2 | value3

    or on seperate lines like this

    value1
    value2
    value3

    Thanks for you help

    1. through the use or two CC i was able to take selected from a multiple select and display them in a table. The same basic principal can be applied to format your output any way you want. I dont want to take away from Alexander, but I know he is busy. So in the mean time you are welcome to review this 3 part article. If you like you may use it, or wait until Alexander has the time.
      http://sharepointhacker.wordpress.com/2010/03/24/choice-field-multiple-select-multiple-columns-part-1/

    2. Hi,
      Sorry for the late reply, here is one solution using the init_fields_v2() function:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      // A multi lookup column with FieldInternalName "MyLookup"
      var myLookup = $(fields['MyLookup']).find('.ms-formbody');
      myLookup.html(myLookup.html().split('>; <').join('><br><'));
      
      /* init_fields_v2
      	Function to make object of all fileds in a unmodified SharePoint form
      	Returned data type: object
      		Object properties: FieldInternalName
      */
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}		
      	});
      	return res;
      }
      </script>
      

      This code splits the HTML and joins it with a <br>

      Alexander

  184. User specific NEW and EDIT aspx pages

    Hello Alexander,

    Imagine: a large list of items: e.g. “Products”, you are a independent seller between producer and customer. The Products have unique Names, but a order number (you use this to order at your vendors) and a sales number (You use this printing on you delivery papers for your customers)

    So you hae a list with three columns (imagine ;)): Product, Order Number, Sales Number

    Why ever, the purchasers should only able to add and edit Product/Order number; the sellers should only be able to add and edit Product/Sales number.

    (In reality, there are more than 100 columns in this view, partially belonging to one of the departments, partially shared)

    I am looking for an ADD/EDIT Script/Form/… which allows to restrict the purchasers/sellers to the columns they are PPR. So Purchasers can not edit sales numbers and vice versa, but are working on the same list.

    Warmest regards
    Michael

    1. PS:

      I can imagine to have a new/edit page for a list defined by a specifiv view, but did not know how to code this.

      Looking at my request above: Puchasers have Purchasers View with Product /Order number and Sellers have Sellers View with Product and sales number.

      Dreaming about a list with more than three columns (three may be solvable by lookups) it would be nice to have a edit/add new functionality only for the fields included into active view.

      Best regards
      Michael

    2. Larry thanks a lot for this link. That will be useful for an other project!
      I need to clarify my request: I am interested in new/edit forms only coming up with the fields from actual view (not user). So, AllItem should edit all Fields, SalesView should only edit Sales fields. It would pretty nice if it is possible to have a general solution working with every view instead of adjusting every view with CEWP code containers. But I am willing to enter them into every view if that is the way to get this running.

      It is also acceptable, if the answer is: Use Sharepoint Designer to set up view specific new/edit pages and jumping to them with a link from sharepoint.

      If we dig deeper into this: if it is possible to have this edit/new based on views it may be helpfull to have some fields in edit mode on read only for all others than owners (and that will then bring up the script you mentioned).

      Thank you for discussion, I would appreciate to go with discussion.

      Kind Regards

      Michael

    3. Hi,
      Interesting approach… I will try to make a solution like this, but unfortunately I’m a bit busy… Stay tuned and i will let you all know if i can get this to work.

      Alexander

    4. Hallo Alexander, I would like to help if it is possible. Would appreciate to help and learn.
      Thank you for being interested.
      Regards Michael

      ( may I ask if you can have a look on my post with this attachments issue?)

  185. Hi Alexander,

    ltns, hope you are doing good. A couple of days ago a colleague came by and asked wether it is possible to execute SQL statements with sharepoint to manipulate lists. I thougt of this for a moment and I couldn’t see a reason why it shouldn’t be possible.

    I’d just take your redirect script to manuipulate the “OK” button of a form and then insert the sql string instead of the new url et voila, case closed.
    Turns out however that I haven’t found a single reference for client-side sql with javascript to have it run when a user clicks ok to save a form.

    Is there a chance to get this running somehow? Jquery has so many addon’s but none of them deals with direct database connections.

    regards,
    Chris

  186. Hi Alex,

    I want to know if it is possible to send an email that contains multiple list items. For example I want to send an email to person A that states person 1,2,3 has successfully completed a task on a sharepoint list. Is this possible? Any help or anything anyone can point me to will be greatly appreciated.

  187. Hey A,

    I know you posted some data on how to prepopulate multiple line text fields. I have been trying to expand on this. I have an intake I use that most of the responses are 1 of 4 general sentences. I have been trying to add some click text that will populate the multiple line field based on what I click, but only change the existing populated text if a new item is clicked.

    Click option 1, multiple line field = option 1, if I now click option 2 multiple line field = option 2, option 1 text is deleted from field.

    I have thought maybe even radion buttons, but I cant either to fire on click and populate field.

  188. Hey Alexander,

    I have a catch-all document repository set up with some mandatory fields that I want the user to specify before they can upload the document. The mandatory fields /metadata (meeting type and meeting date) helps my workflow to route the document to the appropriate meeting site and know when the document needs to be reviewed. Problem is, SP uploads the document and THEN asks for the meta-data. If the user doesn’t supply the meta-data (presses cancel) then the document is still uploaded to SP but is checked-out and only the user can view it (I can’t).

    What I was wondering if JQuery could do is make SP ask for the required data before the upload process and therefore the user would be forced to supply the required fields or the document would not be uploaded and shown on SP. Alternatively, another solution would be so that if they hit “cancel” then the document would be automatically deleted from SP or whatever temp folder it is held in.

    Thanks!!

    1. Hi,
      A couple of possibilities:
      1: Hide the Cancel button
      2: Have a Workflow delete the item if the required field is not filled

      I do not have a jQuery solution other than hiding the Cancel button.

      Alexander

    2. Thank you for the response Alexander:

      1) Since the Update page is used by other doc libraries do you have a suggestion for just editing the cancel button on certain pages? Similarly, regarding how to hide buttons – do you know if it is possible to hide the date-picker control (not the actual textbox – just the calendar icon) in a form?

      2) Unfortunately, I tried this but a workflow won’t kick off b/c the document is never actually uploaded fully. Instead, the document is shown as checked-out and therefore a standard SP workflow doesn’t get kicked off. So I literally have no way of knowing the document was ever posted.

    3. Here is some script from A, some time back to hide the cancel button
      [sourcecode]
      <script type="text/javascript" src="/sites/globalmp/JavaScripts/jquery-1.3.2.min.js"></script>
      <script type="text/javascript">
      $("input[id$=’GoBack’]").hide();
      </script>

    4. Hi,
      You are right, i forgot about the document not triggering a WF upon upload… I did actually write an article about that though…

      Here is a method for hiding the datepicker image:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      $(fields['MyDateTime']).find('img').hide();
      
      
      /* init_fields_v2
      	Function to make object of all fields in a unmodified SharePoint form
      	Returned data type: object
      		Object properties: FieldInternalName
      */
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}		
      	});
      	return res;
      }
      </script>
      

      Put this below the form webpart. The FieldInternalName of the date and time field in this example is “MyDateTime”.

      Alexander

  189. I have a custom SharePoint list, being used as a request form. There are 2 particular fields I would like to use for validation. One Drop Down, one Date Picker, so that the form errors on submit if invalid.

    Based on Drop Down Selection (Choice 1, Choice 2, Choice 3) the date picker needs some validation on form submit.

    If Choice 1, Selected Date must be a Tuesday, and must be at least 7 days from [Today @ noon]
    If Choice 2, Selected Date must be a Thursday, and must be at least 7 days from [Today @ noon]
    If Choice 3, Selected Date must be third Friday of the month, and must be at least 30 days from [Today @ noon]

    Any help you can provide will be greatly appreciated! Thanks!

    1. The number formatting is given from the regional settings in SharePoint. Create a new calculated column with the formula: =TEXT(MyNumber,”0″)

      MyNumber is the name of my field – replave it with your field name.

      Alexander

    1. This will strip off commas in EditForm (place in CEWP below the form):

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      var myInput = $(fields['MyNumber']).find('input');
      	myInput.val(myInput.val().replace(/,/g,''));
      
      
      /* init_fields_v2
      	Function to make object of all fields in a unmodified SharePoint form
      	Returned data type: object
      		Object properties: FieldInternalName
      */
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}		
      	});
      	return res;
      }
      </script>
      

      MyNumber is the FieldInternalName of the field.

      Alexander

  190. Is it possible to hide values in a dropdown of Lookup, choice or the time values? I thought I recently read this was done on a lookup, but cant find it. I need to hide some houre on the time for a date field. is it possible?

    1. Like this:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      var arrOfHouresToShow = ['8 AM','12 AM','4 PM'];
      
      $(fields['MyDateTime']).find('select:first option').each(function(){
      	var thisVal = $(this).val();
      	if($.inArray(thisVal,arrOfHouresToShow)==-1){
      		$(this).remove();
      	}
      });
      
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}		
      	});
      	return res;
      }
      </script>
      

      The date and time field in this example is named “MyDateTime”.

      Alexander

    2. slam dunk. That was perfect! I believe you also did a date compare, Enddat cant be less than start date. I believe it only looks ate the date, not the time. How can I compare dates, including the time?

    3. If you find the script – look at the part with “…= new Date(…”

      Here the date object is constructed like this:
      new Date(year, month, day, hours, minutes, seconds, milliseconds)

      You can read the hour from the select and use it in the constructor.

      Read about it here

      Alexander

  191. Hey A,
    Sorry if this replicated, I cannot see the post.

    I really tried not to bother you with this one, but I have been unsuccessful in locating a solution. I need to calcualte the third friday of the current month. I tried to modify a similar script for a US holiday, but no success. If you have some time can you take a loook and let me know what i missed?

    $(function showThirdFriday(){
    var tFriday; 
      $(this) = new Date();
         $(this).setDate(1);
       // Find first friday.
       while($(this).getDay() != 5){
          $(this).setDate($(this).getDate() + 1 ) ;
       }
       // Add 2 weeks.
       tFriday = $(this).setDate($(this).getDate() + 14 );
       alert(tFriday);
    });
    
    
    1. If you change it like this it will work:

      $(function showThirdFriday(){
        date = new Date();
           date.setDate(1);
         // Find first friday.
         while(date.getDay() != 5){
            date.setDate(date.getDate() + 1 ) ;
         }
         // Add 2 weeks.
         date.setDate(date.getDate() + 14 );
         alert(date);
      });
      

      Alexander

  192. Hey A, thanks for the above code. Great help.
    I have new request, not a hard one. I just cant get all the syntax correct. I have a list view, setup in the Preview Pane style. With the help of jquery I have removed the .ms-formlabels, and the first TR, which contained the Title. The background color is a little dark so I began playing with opacity. I know that this affects the child also, which is my problem. There are several solutions to get around this, but I can implement the solution.

    This is what I have

    $("table.ms-formtable").find("tr:first").hide(); //hide first row
    $("table.ms-formtable").find('td.ms-formlabel').hide(); //hide form labels
    $("table.ms-formtable").find('td.ms-formbody').css({'z-index':'-1','filter':'alpha(opacity=20)','opacity':'0.2'}); //bg opacity
    

    I can not figure out how to wrap the child, or the text in the preview so I can set the css. There appears to be a DIV tag, but cannot confirm if this is always true for each preview. If I can set the css I can off set the opacity of the child.

    .css({'z-index':'1','position':'relative'});
    

    Any thoughts or suggestions?

    1. I’m no expert at this, but i think it will be hard to have a different opacity for a child. Why not just add a brighter background color?

      Alexander

  193. Hi Alex,

    I’ve been frustrated by what should be a simple solution. In Excel I’m able to determine if a task is past due by comparing the start date/time to Now(). Unfortunately, SharePoint doesn’t support Now() as a filter option in a view, so I’m only able to use [TODAY], which only shows tasks when they are at least 1 day past due. Do you know of any JavaScript I could use in a view to show all past due tasks as of that day and time?

    Any guidance you can provide would be greatly appreciated as it would save considerable time in identifying tasks that are passed due throughout the day.

  194. You have great site. I have 2 requests maybe you can help with. Star rating for MOSS or SP 07 and a flyout menu for the top navigation. I know by default the top navigation offers 1 level dropdown (or is that considered 2), but this is not enough. I have tried many different solutions that required modifying the master page, but not the results I need. Is there is a way to add a tab or 2 (maybe more) to the top navigation that pulls data in from a list, that populates the menu based on the list structure.

    Maybe there is a field “Category”, “Level1”, and “Level2″… then the menu builds based on list data.

    thanks Tim

    1. Hi,
      Star rating has been requested many times, but i have not yet been able to find time to do that – i guess you have found this one Ratings for SharePoint lists

      A fly-out like you describe is possible to make, but if you do not put it in the masterpage, you will have to add code on every page where you want it to appear…

      Alexander

    2. I dont mind using the master page to implement, I have not been able to find a good solution. Looking over all the work here, it almost appears that you have built many scripts linking to another list. Just though this would be fairly easy. I do like the Ratings for SP list, but the Stars would be better. thanks for your time.

  195. Hey A,

    I need you expertise again. I am playing with a script from Jan Tielens Search as you type jquery script http://weblogs.asp.net/jan/archive/2009/07/02/sharepoint-search-as-you-type-with-jquery.aspx. By default this searches all sites and i am trying to search a single list or library. I have sent a request, but no response so I did some research and found that this is fairly easy to adjust, the problem is I cannot figure out the correct syntax. in the script line 9-15 it is setup with the search parameters including the scope “All Sites”. in the CAML I read you can add a string to the QueryText. I cant figure it out. in the script line 159 this is the text
    [sourcecode]
    <QueryText language=’en-US’ type=’STRING’ >SCOPE:"" + quickSearchConfig.scope + """ + query + "</QueryText>

    I should be able to add SITE

    [sourcecode]
    <QueryText language=’en-US’ type=’STRING’ >SCOPE:"" + quickSearchConfig.scope + """ + query + " SITE:"mysite"</QueryText>

    but I cant figure this out. Can you shed any light?

  196. Alexander,

    It’s been a while since I’ve been here. I still use loads of the incredible code you’ve developed. Thanks a lot! I’m not sure if what I want is possible, but if it is you are the person to tell me!

    Here’s my request: I use your “tabs” code for display, edit, and new forms. There is an attachment tab. I want to be able to create folders for these attachments – or some other way of organizing the files.

    Thanks as always!

    1. Hi,
      I do not think it is possible to add any folder structure or metadata to the attachments. The attachments are stored in the …/sitename/Lists/Listname/Attachments folder – in a folder named using the list items ID.

      To achieve this you would have to store the attachments in another library and “routing” attachments to that library, linking them to this items ID. Then use some custom code to retrieve the attachments and display them in the list view and in DispForm/EditForm.

      This would require a lot of work and i do not have any examples to give you at the moment.

      Alexander

  197. I want to redirect users to mobile site , if they open main site in mobile page in sharepoint2010?
    can you suggest me any javascript ?

    Thanks In Advance!

    1. am using below JS to mobile redirection ,

      But its not working some of BlackBerry versions example blackberry9000

      do you suggest any other script to do the same?

      Thanks in advance

  198. Hi Alexander,

    Very nice work!

    I’ve spent lots of time searching for a simple way to stuff a date/time stamp into a list field, so that I can capture custom timestamps for specific activities. UTC – 5 would be fine for all. I can generate the string, but can’t figure out how to pass it to the hidden form field, as in “field xx Value=CallmyTimeStamp()”

    I’d love to see you post something; I can’t believe there isnt huge demand for this…

    Tim

  199. one more quick request. How can you hide the fields on a New Edit form of a calendar FieldType=”SPFieldAllDayEvent” and/or FieldType=”SPFieldRecurrence” some reason I think the function misses these. I dont understand regex to figure this one out.

  200. hate to bug you again. I am trying to build a presave function to check the value of a radio. when the field is a dropdown I can get it to work with this
    [sourcecode]
    var myAccurate = $(fields[‘Accurate’]).find(‘select’);
    var myAccurateVal = myAccurate.find(‘option:selected’).text();
    function PreSaveAction(){
    if(myAccurateVal==’Yes’){
    if(confirm("Are you sure field "Accurate" should be "Yes"?")){
    return true;
    }
    //return false;
    //myAccurate.focus();
    }
    }

    I searched all you request posts but could not find the syntax. I found checkbox but not radio. If you have a minute can you help?

    1. Hi,
      I have been cut off from the Internet for nearly 18 hours caused by someone digging over my ISP’s main cable.
      Do it like this:

      function PreSaveAction(){
      var myAccurateVal = $(fields['Accurate']).find(‘input:radio:checked’).next().text();
      	if(myAccurateVal=='Yes'){
      		if(confirm("Are you sure field "Accurate" should be "Yes"?")){
      			return true;
      		}
      		//return false;
      		//myAccurate.focus();
      	}
      }
      

      Alexander

    2. Hey A, sorry if duplicate. I tried to post this yesterday but I dont see it. I am still working with the presave function. When I try to get the date val in an alert the val is blank

      function PreSaveAction(){
        var myStartDateVal = $(fields['StartDate']).find('input:first').val();
        alert(myStartDateVal);
      }
      

      I’m I missing something?

  201. Hi Alexander,

    A humble request for your masterful code-wizard skills.

    I’ve got a SharePoint 2007 Blog site rockin in my Intranet environment at work, also got you vertical scrolling web part which on the main page showing the latest posts and the Hit/Like Counter on each Blog Post.

    What I’m trying to find a solution for, is a “Related Posts” web part, which is displayed next to each blog post, which can be either a list of posts from the same category or even posts that can use a Search Query to display “Related Posts”.

    I’ve tried Googling “SharePoint blog related posts” and it displays every Blog site on the web… frustrating.

    Can this be accomplished using the Data View Web Part?
    Do you know of or are you able to provide a solution for this common ailment in Blog Sites?

    Your time and efforts are much appreciated and I think you deserve some kind of Charity Medal for the free solutions you provide. 😉

    Thanks, Brett.

    1. Have you tried the “Search Box” and “Search Core Results” web parts? These are much easier to use then defining a search scopes and give you the ability to set specific parameters. I just started playing with this after abondoning the Search Scopes and I am very pleased with the results. I believe you may be able to tweak these to fit your needs. If interested let me know and I will post a quick tutorial, not to take away from A’s great work.

  202. Sounds great Larry, anything to get something working on my site.
    I’m interested in how you can have the search query based on the Category of Video is being watched at the time and display the results in a web-part.
    I did see a working solution at the SP Conference in Sydney, Oz, last week but it was for SP2010 and he used a Search Results Web Part also.
    Hit me up when you have something and I’ll give it a crack.
    Cheers, Brett

    1. I haven’t had the time to write up a full detailed descrition so here is the infomerical cut.
      1. In Site Actions >> Site Setting, turn on SharePoint Search Webparts
      2. For practice create a Web Part page. Later you can export/import or recreate in any other page
      3.Add two Web Parts
      a. Search Box
      b. Search Core Results
      4. Modify the Search Box Web Part
      5. Select option “Do Not Show Search Scopes in Dropdown”
      6. For the Query Textbox, get the URL for your list/library. No last slash. Example: http://path/Library/Forms/AllItems.aspx URL = “http://path/Library”
      7. Additional Query Terms, ‘site: “http://path/Library”‘.
      this is important how you format. two parts
      site: and the URL in quotes. You need the quotes
      8. Uncheck append Additional Terms to Query.
      9. Give it a name
      10. Target, change to current page, can use relative URL.
      11. click OK

      give it a run. once you get it working there are other tweaks you can add and remove to modify your results.

  203. Thanks a bunch Larry, I’ll give this a try at work 2morro and let you know.

    Off topic Q for the floor: Does anyone else, ie: SP Designers/coders, constantly think about ways to improve an SP site? While driving, watching TV, during conversations, going to sleep etc… 🙂

  204. Larry, Got it working but I still have to physically type in a Search Query to display the results.
    I’m gunna try a solution using the Query String (URL) Filter and see if I can display the Posts. Cause all I need is to display the list of posts from that Category of the Post that is being displayed.

  205. Hi Alex,

    another challenge from me…I’ve got a doc lib with two folders and basically three types of groups.

    Folder A – Content visible to Group A and C,D,…
    Folder B – Content visible to Group B and C,D,…

    In other words, Group A and B only see the content of their respective folder whereas all other groups see the content from both folders.

    The views have been defined to show content without folders at all, just using metadata to sort the information.

    That’s where my problem starts. When someone uploads a document to the lib – in a non folder view – it is always placed in the ‘root’ folder instead of ‘automatically’ in the Group A or B folder. I don’t want to change the view to display folders so I’m looking for a way to change the upload to go to Folder A when someone from Group A uploads a document and to Folder B when someone from Group B uploads a document.

    I’ve tried setting the rights for the root folder to read only but then the “upload” menu vanishes and no upload at all is possible for A or B. Can you think of a way to have the uploads go to the correct folder automatically, depending on the group membership? Group C,D… have access to a view that displays the folders.

    thanks,
    Chris

    1. Hey Chris, I know A is busy so I thought I would throw in my 2 cents in. I remember finding an article on EUSP some time back related to created folders that linked to views, not the entire scenario you’re looking for. So I did some research and I found several articles that might provide you with what you need. The first 2 part article is about the use of content organization
      Part 1: http://blogs.technet.com/b/speschka/archive/2009/10/30/sharepoint-2010-content-organizer-part-1-a-cool-new-feature-for-managing-your-content.aspx

      Part 2: http://blogs.technet.com/b/speschka/archive/2009/10/30/sharepoint-2010-content-organizer-part-2-organizer-settings.aspx

      then I found an article that uses the SP WF to copy items into doc library folder using SPD Activities on codeplex:
      http://social.msdn.microsoft.com/Forums/en/sharepointworkflow/thread/2a3c5e5b-4fb2-4d8a-8e1b-0d56d032fece

      I hope these are helpful.

    2. Larry, sorry for the really late reply. I’ve had a look at the site the day you posted them but was distracted by someone so I forgot to come back and report my findings.

      The technet links look promising as far as I understand the content the ‘content organizer’ will add some sort of ruleset filtering ability to doc libs which might be worthy for further investigation as soon as I have access to a 2010 version 🙂

      The msdn link has some good ideas, unfortunately not usable for me, since a) I can’t use spd at work and b) I’m not skilled enough to code what might be needed to accomplish the task.

      So…I kinda moved back to ‘old school techniques’ by creating another view called “upload” which only shows the two folders and writing a howto for the users to use this view and the appropriate directory to upload their files.

      et voila, it’s working 🙂

      Chris

  206. Is there a way to hide the appended comments to a multipe line field with version control. Actually can it a a click hide/show, and can it display the last comment by default? click it the see all pervious comments.

    1. I saw this post and figured this is easy to do. Well not really. I am close. The is something about the comments that i can’t figure out. They all appear to be wrapped in a div, but not all of them are hiding for me. This code will toggle the comments (most of them) on click of the first one. Maybe A can lend a hand.

      <script type="text/javascript" src="/path/jquery-latest-min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      $(fields['MyComment']).click(function(){ 
      	$(fields['MyComment']).find('.ms-formbody div div:children("div")').toggle();
      });
      
      function init_fields(){
      var res,myMatch,disp,fin,type;
      	res = {};
      	$("td.ms-formbody").each(function(){
      	myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);	
      		if(myMatch!==null){
      			// Display name
      			disp = myMatch[1];
      			// FieldInternalName
      			fin = myMatch[2];
      			// FieldType
      			type = myMatch[3];
      			if(type==='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type==='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}		
      	});
      	return res;
      }
      </script>
      
      
  207. Hi All, I’m trying to find two solutions in my SP 2007 Intranet.

    1: Mega-Drop Down Menus on the TopNav bar possibly using JQuery/CSS. Has anyone got a working solution or code I can throw in my Default.Master?
    I’ve looked over this post: http://tothepoint.inproc.com/creating-mega-drop-down-navigation-in-sharepoint-2007-with-jquery/
    but his instructions are poorly written compared to Alexanders’ and incomplete. (No JQuery)

    2: A pre-configured Button that auto subscribes the current user to a List (Posts in a Blog). Instead of the user clicking on Actions, Alert Me, choose what settings, click OK, all they do is click a button and bam, they’ve set the Alert.
    This Blog sorta explains something like that but not exactly what I’m after. http://moblog.bradleyit.com/2009/03/cross-iframe-scripting-in-sharepoint.html

    If anyone can provide some help with these, that would be splendid.

    Thanks,

    Brett.

    1. Hi,
      The “Mega-dropdown” might be something i will look at in the future, but the auto subscribe is not possible using webservices so i do not think this is possible using client side code.

      Alexander

  208. Hi Alex:
    Here’s what I’m trying to do. On a SharePoint page, the user sees a split page with the first of many documents OPEN on the left and sees a NewForm on the right. She reviews each document for specific items and checks yes/no, etc. on the NewForm.

    When done with document #1, the user saves the NewForm, clicks a left arrow to advance to and open the next document and a new NewForm opens to start the 2nd review. The NewForm data is stored in a List. The documents are preferable stored on a Shared Directory.

    Ideas? Thanks-

    Charlie Epes
    Buffalo, NY

    1. Hi,
      You might be able to do this using iframes and have two refreshable pages side by side, but do not think i can help with this one, sorry.

      Alexander

  209. I have been working on a script that will auto expand all calendar events in a calendar view. I have found bunches of scripts that come close but none of them manage it all. What i have found with the scripts is they do not work on recurring events. Infact when the script is ran recurring events are no longer visible.
    Here is one
    [scriptcode language=”javascript”]

    /*
    //Expant all events onload
    var yScroll = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop
    var y = window.innerHeight || document.body.clientHeight || document.documentElement.clientHeight
    var xScroll = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft
    var x = window.innerWidth || document.body.clientWidth || document.documentElement.clientWidth;
    var cover = document.getElementById(“cover”);
    cover.style.height = (y + yScroll) + “px”;
    cover.style.width = (x + xScroll) + “px”;

    function expand() {
    if (document.referrer != location.href && !location.href.match(/CalendarPeriod=((week)|(day))/i))
    { GetMonthView(‘11111111’); }
    else { cover.style.display = “none”; }
    }
    window.onload = function() { expand(); };

    [/scriptcode]

    here is another
    [scriptcode language=”javascript”]

    _spBodyOnLoadFunctionNames.push(“ensureExpanded”);

    function ensureExpanded()
    {
    var links = document.getElementsByTagName(“a”);
    for(var i = 0; i<links.length; i++) {
    var s = links[i].innerHTML;
    if(s.indexOf("more items") != -1)
    {
    GetMonthView('1111111');
    return;
    }
    }
    }
    [/scriptcode]

    can you see what needs to change to get the recurring events to work the same? or maybe you have your own.

  210. Hey Alex,

    i need a JavaScript , where i can validate a share-point list column type single line text to enter only numbers.

    Thanks in advance

    1. here is a script from A:

      <script type="text/javascript" src="/test/English/Javascript/jquery-1.4.2.min.js"></script>
      <script type="text/javascript">
      fields = init_fields_v2();
      
      // Allow numbers only in text fields
      // Array of FieldInternalNames to lilmit to numbers only
      var arrToCheckForNum = ['Title','Num'];
      // Array of length of input string - set to 255 if you do not want to limit input length. Corresponds to the same array index in the "arrToCheckForNum"
      var lengthOfInputNumber = [9,2];
      
      $.each(arrToCheckForNum,function(idx,item){
      $(fields[item]).find('input').css({'width':'75px'});
      	$(fields[item]).find('input').keyup(function(e){
      		var thisVal = $(this).val();
      		thisVal = thisVal.substring(0,lengthOfInputNumber[idx]);
      		$(this).val(thisVal.replace(/[^0-9]/g,''));
      	}).blur(function(){
      		var thisVal = $(this).val();
      		thisVal = thisVal.substring(0,lengthOfInputNumber[idx]);
      		$(this).val(thisVal.replace(/[^0-9]/g,''));
      	});
      });
      
      /*
        LastMod: 07.05.2010
      */
      function init_fields_v2(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			res[fin].FieldDispName = disp;
      			res[fin].FieldType = type;
      		}
      	});
      	return res;
      }
      </script>
      
  211. Hi, is it possible to have a dynamic Web Part title? So for example, I have a List that contains projects and their status. On my home page I have a view exposed that filters on the projects in Red status. The title is “Current Red Projects” but I would it to say something like “Current Red Projects (8)” where the count is dynamically appended to the title.

    Thanks for all you do!

    1. Hi,
      It is possible, but you would have to use JavaScript, counting the items and updating the title.

      If you use FireBug (Firefox) or Developer toolbar (IE) you can inspect the page to find what to count and where to put the result.

      Send me a screenshot and i can see if i throw something together.

      Alexander

  212. Hi Alex,

    I’ve got a new idea to improve things at work but as always, I’m lost when it comes to code it. My colleagues have to maintain two lists, one for orders, a second for inventory. Both contain similar info so they have to enter some info twice.

    The idea is to create a button, e.g. in dispform of an order list entry which will copy selected (pre selected, not user selectable) fields to the inventory list, similiar to the cascaded dropdowns with source and target field mapping.

    Using the button will have to check existance of the entry in inventory list based on the selected fields, if found update, if not create new. Best would be if also a link to the inventory entry could be created in the order entry.

    Sounds weird, does it? 🙂
    Chris

    1. Hi,
      I would need some more details or a quick sketch to get the full picture. It is definitely possible, but it might be a little to custom made to be of general interest.

      I could look at it and maybe do a custom job for you?

      Alexander

  213. Hey A, Been a while and hope you are well. I have enjoyed using and modifying your scripts. I have ran into a little issue, no fault of your’s. I am running several of your script on a single page. the page load performance has been drastically reduced to a crawl. I can live with a slow page load, but the problem is the page goes white and it looks like it is finished loading. Perople think it is broken because there is not way to determine it is still loading. I was thinking, is there a way to initially display the SP gears image on the page untile the page is loaded then hide the image? I have been trying to get this to work by added the image to the page and trying to hide it by ID in the document.ready function, but no success. I know there easey thing to do is remove the scripts, actually built it in infopath, but too late for this now. Is there a way to display a loading image before the page is completely loaded?

    1. Hi,
      To have the image rendered *before* the page has finished loading is not possible, but you could do it by delaying the call to the “long running process” by a millisecond or two to ensure the picture is displayed before freezing the screen.

      Alexander

    2. Hi,
      Something like this:

      <style type="text/css">
      .divOverlay{
      	padding-top:250px;
      	font-size:24px;
      	text-align:center;
      	filter:alpha(opacity=80);
      	-moz-opacity: 0.8; 
      	opacity: 0.8;
      	width:100%;
      	height:100%;
      	background-color:silver;
      	position:absolute;
      	top:0;
      	left:0;
      }
      </style>
      
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
      <script type="text/javascript">
      var buffer = [];
      	buffer.push("<div id='myCustomOverlay' class='divOverlay'>");
      	buffer.push("Please wait while loading...");
      	buffer.push("</div>");
      	$('body').prepend(buffer.join(''));
      setTimeout(function(){		
      	/* 
      		Put the call to the code here.
      		You must remove the overlay when your code has finished using this line:
      		$("#myCustomOverlay").remove();
      	*/
      },10);	
      </script>
      

      Alexander

    3. it is amazing how you spit this stuff out. So what would cause the overlay not to close or be removed. It seems to work, except not removing.

  214. Hi Alex,

    im looking for a way to hide Columns in the DispForm and EditForm.
    Something like you described here: https://spjsblog.com/2010/02/16/filter-list-view-based-on-membership-in-sharepoint-group/

    But the columns should only be Visible to a person that is chosen in a peoplePicker Column in the same ListItem. Additionally the column should be always visible to specific Persons/Groups.

    Something like this:

    If (CurrentUser==PeoplePickerColumn || CurrentUser==CEO)
    showColumn();

    Can this be achieved with one of your scripts?

  215. Do we have any javascript to disable edit item on a sharepointlist?

    i want to allow users to add the items but not editing items.

    any thoughts?

    1. Hi,
      You can override the ecb-Menu, but this would be for that page only and users have multiple entries – including writing the URL directly. I would suggest putting some code in EditForm itself to “redirect” the users away – to DispForm for example.

      Alexander

    2. I believe you can create a custom access level and remove the Editing list item. Then apply it to that list for all users. It will allow you to create new items, but not editing. DO NOT modify an existing access level, copy or create a new one to edit.

    3. Hi,
      You are right Larry, but be aware that running a workflow (that modifies the current item) requires edit rights.

      Alexander

  216. Hi,

    I posted this request as comment in one of your post. I am posting it here again.

    I am working with a workflow (using AgilePoint workflow for SP2010) which uses list default edit form as workflow task form. It shows and hides fields based in workflow configuration.

    Say I have task A, B and C. In task C I show certain fields (which are hidden in task A and B) and in this task this field is mandatory. If I set field as mandatory in SP2010, the form expects the fields to be entered even in task A and B (where they are hidden).

    Is there a way to set fields as mandatory from javascript? I get the task Id from query string, I feel I may be able to use this value to check for the field and check if value is entered by the user.

    Thank you.

    Cheers.

  217. Hi Alexander,

    Got an awesome request for your mad skills.
    Are you able to provide a Javascript/Jquery code for a Comments Box Web Part? So it can be added to any page, list or library?

    I’m thinking you could set it like the Poll web part, where the Admin can specify the ID Name for each Comments Web Part instance, which will allow the user comments be allocated to the corrent web part.

    So it would function exactly like the Comments Web Part in a Blog Site, using the authenticated user credentials and/or anonymous comments if you desire.

    There are a few Posts mentioning DVWP’s and SP Designer but I’m hoping to use a Javascript based solution.

    I’ve looked everywhere for this function and closest I found was this Post.
    http://devgrow.com/simple-threaded-comments-with-jcollapsible/

    Many thanks for your time and efforts,

    Brett

    1. Hi,
      Thank you for your donation.

      I will look at this and see if i can put this together. A few questions:
      What type of comment-field: single line or multi line, rich or plain text?

      Shall the comment be visible above/below the comment field?

      If you have any specific ideas, please e-mail me a sketch.

      Alexander

  218. Alexander,

    Thanks for everything you do on this site. I find myself coming to it almost everyday for your javascript advice and help. It’s helped me out numerous times at work for a few of our sites.

    I do have a question if you aren’t too busy with other requests.

    I’m trying to modify the “Upload” button in a Doc Library. I would like to 1) change the name of it to something less vague, and also 2) remove the “Upload Multiple Documents” link completely.

    I know this can be done by accessing the Central Admin, but I don’t have access to that since it’s a bit above my pay grade (if you know what I mean). If you could help, I would be grealy appreciative!

    Thank you so much,

    Jay

    1. Hi,
      The upload page is shared between all libraries in all site collections on the server. You cannot modify the page for one library.

      I have however done a “hack” to make a custom upload page using an iframe and some jQuery to hide all unwanted bits and pieces. I will try to find time to write a short article on it.

      Alexander

  219. Hey A, it has been a while again, but I always enjoy coming back to this site. Every time I return I find a piece of code I can use some where even if only one line. Today I have a request for knowledge. in ShP 2010 the new and edit forms open up in a litebox type of a window. I have a few lists that link to a single list by a lookup column. I have added a link below the field description so the user can click it to add an item to the parent list. It even opens in the popup like window. the problem is even if an item is added it is not refreshing the field to show the new value. I have to close the form and reopen it for the new item to show. Is there a way to refresh the popup so the new value will display?

    1. Something else I noticed. It doesnt matter if the form is in modal or the newform.aspx. when user clicks to add an item to the lookup and returns to the page it does not update. I can refresh the newform and is still will not display. I guess this is a bit more then a refresh. Maybe have to reload something, the data thaty populates the fileds? any thoughts would be helpful as always.

    2. Hi Larry,
      Thank You for the donation.

      I did a test using two lists. I made a lookup column from list A to list B. I then opened lits A and saw one item in the lookup field. I left the dialog open and in a new tab added a new item to list B. Upon return to List A’s dialog – the lookup column did not update (as expected), but when i right clicked in the dialog and reloaded it, the lookup column showed the new item.

      Is this not the way you found it?

      I do not have a way of reloading the lookup column without reloading the form.

      Alexander

  220. Hello Alexander,

    Using the Content Web Part and JQuery combination is great for ad hoc styling and effects for lists but is less accessible to end users.

    One possible approach could be to place the script in the itemstyle.xsl and then the script could be applied to CQWP and Summary Links simply by selecting it as a display option.

    For example, if I had a list containing a title and description, it would a powerful feature to simply select an accordian style to display the titles and then selectively reveal the desriptions via the accordion effect.

    This would be great for News, FAQs etc. where the description might be long but you would like to see the complete list of headlines or questions.

    Is this feasible and could you provide a worked example ?

    Cheers
    John

  221. Hey A,
    Is there a way to add some kind of functionality that would allow time tracking? When you open the form to create an item, a timer runs, maybe visible, maybe not, and when a status or task name changes the timer writes this amount to another field (maybe workflow). May there are 6-10 tasks, each item has there own time field, based on the task it will update or add time to that field.Maybe what I am looking for is the timer, a way to grab that data and a way to reset or restart the timer.

    1. Hi,
      I do not think this is feasible using client side code. The timer would exist only in the “browser window” and a refresh of that page would restart the timer. I believe a workflow could be done, but 6-10 timers in one item might be a bit messy.

      Alexander

  222. Is there a way to generate a dynamic link to the editform and hove it open in the modal for SP 2010? I am trying to build links back to the source item from different site, but I can not make it open in the modal. do you have a way using the calculated field that can generate a link back to an edit form that opens in the modal for SP2010?

    1. Tim,

      I recently have been working on something similar and was able to achieve this. Without taking anything away from Alexander. Through the use os Christophe script HTMLcc, 2 CC and a small Script I was able to generate a modal popup bak to the edit or disp form.
      I created a CC call URL, this contained the link to the editform
      [sourcecode]
      ="http://sitename/Lists/ListName/EditForm.aspx?ID="&%5BID%5D

      I was already generating an ID using a workflow, so It was visible in the CC. I am sure there are other ways to grab the ID.

      Second CC had my link formula and an edit image so it looked like SP
      [sourcecode]
      ="<div><a href=’"&[URL]&"’ onclick=""return OpenDialog(‘"&[URL]&"’);""><img border=’0′ alt=’Edit’ src=’/_layouts/images/edititem.gif’ /></a></div>"

      I add this CC to a view. On this view I add the 2 scripts in a CEWP
      HTMLcc
      and the modal. I can not rememeber the source but if you search I am sure you will find it.
      [sourcecode]
      <script type="text/javascript">

      //User Defined Function to Open Dialog Framework
      function OpenDialog(strPageURL)
      {
      var dialogOptions = SP.UI.$create_DialogOptions();
      dialogOptions.url = strPageURL;// URL of the Page
      dialogOptions.width = 750; // Width of the Dialog
      dialogOptions.height = 800; // Height of the Dialog
      dialogOptions.dialogReturnValueCallback = Function.createDelegate( null, CloseCallback); // Function to capture dialog closed event
      SP.UI.ModalDialog.showModalDialog(dialogOptions); // Open the Dialog
      return false;
      }

      // Dialog close event capture function
      function CloseCallback(strReturnValue, target)
      {
      if (strReturnValue === SP.UI.DialogResult.OK) // Perform action on Ok.
      {
      alert("Issue has been submitted!");
      }
      if (strReturnValue === SP.UI.DialogResult.cancel) // Perform action on Cancel.
      {
      alert( "Request Canceled!");
      }
      }

      </script>

      The reason I went this route is I used another script of Christophes Cross Site Snap Shot. It was in the cross site view, none of the pages would open in modal. This work around got me there.

      if you have any questions let me know.

  223. Hey A,
    I have a good request for you. I would like to build a menu structure using a SP List. JQuery has a plugin called Superfish http://plugins.jquery.com/project/Superfish. looks like it can create a great menu structure with multiple levels. If the menu items could be maintained in a list that would make it easier for the enduser to maintain it.
    Let me know what you think.

    1. Hi,
      Finally i got to look at this one – have you done anything regarding this yourself?

      I will be posting an article on this in the beginning of next week.

      Alexander

  224. Hey A,

    I am stuck on a small JQ issue. I know you stated you dont really work with calendars, but I am stuck. I want to launch the event in a new window. I noticed there already is a target set to “_self” I add this
    [sourcecode]
    <script type="text/javascript">
    $(document).ready(function() {
    //alert($);
    $(‘.ms-cal-monthitem a[href^="/SiteDirectory/marketing/ce/Lists/Calendar/"]’).attr({target: "_blank",cursor: "hand"});
    });
    </script>

    and I can view code and it changes the target to “_blank”. my problem is it wont oopen in a new window. Can you provide any input?

    thankls

  225. Hey A,

    I need to pick your brain. I am using jquery to pull a filtered set of data from a list. It is using caml to get the filter. What I what to try and do is create a rolling date filter. either pull items from last month, last 3 months or last quarter. I know from within caml this may not be possible.but I figure if I can add calculated columns that either return MMYYYY or QtrYYY, there should be a way to to get last “Month” or last “Quarter”.

    If anyone can do this I know it would be you. Again I dont need the entire solution. I am already pulling data down with a caml query. I want to figure aout a way to filter that date data

    1. Also if there is a way to use external data, like from a dropdown where the user can input and filter. The date is really killing me. having the ability to show last month or last quarter by default would be very kool

    2. Hi,
      Try something like this:

      <select onchange="filterCAML(this)">
      	<option value="">Select quarter</option>
      	<option value="q1">Q1</option>
      	<option value="q2">Q2</option>
      	<option value="q3">Q3</option>
      	<option value="q4">Q4</option>
      </select>
      
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
      <script type="text/javascript">
      
      function filterCAML(elm){
      	var today, val, ds, de, offsetMin, offsetMax, camlBuffer;
      	today = new Date();
      	val = $(elm).val();
      	switch (val){
      		case 'q1':
      			ds = new Date(today.getFullYear(),0,1);
      			de = new Date(today.getFullYear(),3,0);
      		break;
      		case 'q2':
      			ds = new Date(today.getFullYear(),3,1);
      			de = new Date(today.getFullYear(),6,0);
      		break;
      		case 'q3':
      			ds = new Date(today.getFullYear(),6,1);
      			de = new Date(today.getFullYear(),9,0);
      		break;
      		case 'q4':
      			ds = new Date(today.getFullYear(),9,1);
      			de = new Date(today.getFullYear(),12,0);			
      		break;	
      	}
      	offsetMin = Math.ceil((today-ds)/86400000);
      	if(offsetMin<0){
      		offsetMin = 0;
      	}
      	offsetMax = Math.ceil((today-de)/86400000);
      	if(offsetMax<0){
      		offsetMax = 0;
      	}
      	camlBuffer = [];
      	camlBuffer.push("<Where>");
      	camlBuffer.push("<And>");
      	camlBuffer.push("<Gt><FieldRef Name='Created' /><Value Type='DateTime'><Today OffsetDays='-"+offsetMin+"'/></Value></Gt>");
      	camlBuffer.push("<Lt><FieldRef Name='Created' /><Value Type='DateTime'><Today OffsetDays='-"+offsetMax+"'/></Value></Lt>");
      	camlBuffer.push("</And>");
      	camlBuffer.push("</Where>");
      	
      	alert(camlBuffer.join(''));
      }
      </script>
      

      Alexander

  226. Hi Alex,
    I hope your sumer is going well. Do you know of a web part or a solution that would list all sites in a collection that a user has permission to see? For example, if the collection has 100 sites and i have permission to view, edit, contribute to 25 of them, the list or links web part would show “my 25”?

    Thanks,

    Charlie Epes

    1. Hi Charlie,
      I do not have a JavaScript way of doing this. If you try to iterate trough all sites, you would get a login prompt when you hit a site you did not have permission to view. I do not know how to suppress this login and skip the site.

      Alexander

  227. Hello Charlie, I have had the same question in our company environment (2007)´. I found a Microsoft fix/update, which was not installed from the IT group ( I am only a user….). It is a OOTB solution.
    After installation, now the user have (if they had corresponding privileges) a right mouse click: Show effective permissions on a item, also it is possible to check this forlist or libraries (again, if the user have the privileges).

    Sorry, I do not remember the number/name of the fix/update.

    May be, that this link will help:
    http://office.microsoft.com/en-us/windows-sharepoint-services-help/check-permissions-for-a-user-or-group-HA010362860.aspx

    Kind regards
    Michael

  228. Hi Alexander,
    I have a Content Editor Web Part with a number of (the basic setup is a grid) containing name and title of employees in my Company. I would like to use tooltip/mouseover to preview a picture of the person. All images are stored in a separate Picture gallery on the same site.

    I have seen all your other tooltip articles, but I am struggling to customise them for my needs. Can you please help me with this request?

    Thank you in advance!

    1. Hi Alexander,
      Yes I have, but if I understand the code correctly, the tooltip image is retrieved from the URL or the link. In other words, the “IMG” link from the Custom List is pointing to the .jpg and the tooltip allows to preview the image/link. This is great, but not what I need.

      Have a look at the image below: http://i52.tinypic.com/b715ld.png When I hover on the red box (a with a unique ID), I want an image to be previewed from a Pictures repository within the same SharePoint site. The images names are named .jpg. This is different from the code you have suggested because the does not link directly to an image.

      I am sure this is a “fairly” easy thing to do for you, but I am really not a Javascript expert…

      Please let me know if you need any more details. Thank you again!

    2. Hi,
      Something like this:

      <table id="myTable">
      	<tr>
      		<td class="myClass"><span onmouseover="imagePreview(this)">Bob</span></td>
      		<td class="myClass"><span onmouseover="imagePreview(this)">Sandy</span></td>
      	</tr>
      	<tr>
      		<td class="myClass"><span onmouseover="imagePreview(this)">Carl</span></td>
      		<td class="myClass"><span onmouseover="imagePreview(this)">Bill</span></td>
      	</tr>
      </table>
      
      
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript">
      
      function imagePreview(elm){
      	var imgName = $(elm).text();
      	var imgUrl = "/test/english/images/"+imgName+".jpg";
      	$("body").append("<img onmouseover='$(this).remove()' id='preview' src='"+ imgUrl +"' alt='Image preview' border='1' />");
      	var obj = $("#preview");
      	var offset = $(elm).offset();
      	var winHeight = $(window).height();
      	var winWidth = $(window).width();
      	var scrollLeft = $(window).scrollLeft();
      	var scrollTop = $(window).scrollTop();
      	var objHeight = obj.outerHeight();
      	var objWidth = obj.width()+15;
      	if(((winWidth+scrollLeft)-offset.left)<objWidth){
      		offset.left=((winWidth+scrollLeft)-objWidth);
      	}
      	var maxHeight = (winHeight+scrollTop)-offset.top;
      	if(objHeight>maxHeight){
      		if(offset.top-scrollTop>objHeight){
      			offset.top=offset.top-objHeight-20;
      		}
      		height = (objHeight<winHeight)?objHeight:winHeight;
      	}
      	obj.css({"position":"absolute","top":(offset.top+20)+"px","left":offset.left+20})
      	.fadeIn("fast");
      };
      </script>
      

      Alexander

    3. Hi Alexander,
      Thank you so much for this. I have slightly modified the code to get the unique ID of the person

      Row 3
      Bob

      Row 16
      var imgName = $(elm).attr(‘id’);

      Now I am stuck with the following problems:

      1 – The image appears instantly. It appears that the fadeIn() function doesn’t work as expected, even if I change the value to “slow”
      2 – The image is stuck in a position and does not follow the mouse (I have a seen a ‘moveToMousePos’ function you have developed, but I am not able to modify it for this exercise)
      3 – I need a onMouseOut function to fade out the image

      Thank you so much in advance. In the meantime, I have moved some money to your PayPal account to finance your wife’s flowers! 🙂

    4. I guess you have disabled the HTML tags. For the update in Row 3 above, it should look like

      [sourcecode language="html"]
      <td class="myClass"><span onmouseover="imagePreview(this)">Bob</span></td>
      </code>

    5. Hi Alexander, I have just realised that the code above doesn’t always open the “tooltip” but it tends to append the image to the bottom of the page. Every time the tooltip is supposed to open, an image is added to the list. Now I am left with a page that contains ~50 images at the bottom.

      Any suggestions?

    6. Hi Alexander, unfortunately no. I am still experiencing a few issues and the code doesn’t work as it should. It partially works on one of my websites, but not on SharePoint. Do you have an email address or similar where I can send you my code? Maybe you will be able to identify the problem…

  229. Hello Alexander,
    Do you have any solution for incoming emails to lists or document libraries? When someone sends an email to a list/ doc lib (from LN for example) the email is saved as *.eml and so the header and attachement are not included with the body..
    I didn’t find any posts regarding this topic although this matter is spread..
    Please let me know if you need further info.
    Thank you in advance

  230. In my custom list, I have multiple entries with similar data, except one field.

    When I create a new Item, I have to create new entry with the same data except one for each input.

    I’ll take one simple example. I have entries like these

    Europe English Sp2010
    Europe Spanish Sp2010
    Europe German Sp2010
    Europe Italian Sp2010
    Europe French Sp2010
    Europe Portuguese Sp2010

    As of now, I have to create multiple newt for inputting this information. I know about datasheet view but that is not the point.

    Is it possible to have multiple input entries based on number of checkboxes I select.

    Lets say, for new entry(Continent), I select Europe. In checkboxes I select all above languages and click ok. It should be able to create six new entries with different languages.

    If I select Spanish and Portuguese only(from checkboxes), then it should create only two items with two lang.

    South America Spanish Sp2010
    South America Portuguese SP2010

    Thanks for your time.

    1. Hi,
      I’m very sorry to have delayed this answer so long. This is possible to make, but it might not be of public interest. I could do it for you, but it would be a custom job for you. If you send me some sketches of what you want I can make an assessment of the time necessary to make it.

      Alexander

  231. Alexander, a client has complained about the fact that when you change months in a SharePoint calendar (or do anything?), it generates a page refresh.

    I’m wondering whether jQuery ajax would be a solution for that?

    Thanks,
    Michael

    1. Hi,
      It is nothing to be done about that as the refresh is necessary to get information from the server. The calendar acts like a paged list view – only the items visible are loaded, and if you want another set of items you must send a new request to the server.

      Alexander

  232. Good Day A, I am working on a solution to dynamically load a list view from one of many lists. I have about 40 individual lists. I want to create a simple table of contents with links to a data sheet view for each list. when I click the link I want to load it in the same page like an iframe. I dont want to use an iframe because of all the sharepoint page elements loading in the frame. is there a way to load a editable view of a list from a link of dropdown?

    1. Hi,
      I do not think this is possible without an iframe. You could however trim away the “access” when loading the iframe by doing a jQuery “find and hide” exercise.

      Let me know if you need any help.

      Alexander

    2. Are you saying when I load the page I could hide the elements that load in the iframe? Which out going thru all the elements how couold I address this? also if this is 2010, could I take advantage of the modal window with less effort?

    3. Hi,
      Try something like this:

      <input type="button" value="load" onclick="loadListView()">
      <div id="placeholder"></div>
      
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript">
      
      function loadListView(){	
      	$('#placeholder').html("<iframe id='customListView' src='/test/English/Lists/ECBCopyItem/AllItems.aspx' width='1100px' height='800px'>");
      	$('#customListView').load(function(){
      		hideContents();
      	});
      }
      
      function hideContents(){
      	$('#customListView').contents().find("#LeftNavigationAreaCell").hide();
      	$('#customListView').contents().find(".ms-titlearealeft").parents('tr:first').hide();
      	$('#customListView').contents().find(".ms-globalTitleArea").parents('tr:first').hide();
      	$('#customListView').contents().find("#onetIdTopNavBarContainer").parents('tr:first').hide();
      	$('#customListView').contents().find(".ms-globalbreadcrumb").parents('tbody:first').hide();	
      }
      </script>
      

      Alexander

    4. Hey A,
      one more question on this. If I had multiple pages I wanted to load, individually, I want probably want a more generic function, right? what changes would I need to make to the loadlistview so I can pass differnt url’s based on the link?

      would this work for the function?

      function loadListView(src,id,h,w){
          $('#placeholder').html("<iframe id='"+id+"' src='"+src+"' width='"+w+"px' height='"+h+"px'>");
          $('#customListView').load(function(){
              hideContents();
          });
      }
      

      and a link like this?
      [sourcecode]
      <a href="javascript: loadListView(‘/test/English/Lists/ECBCopyItem/AllItems.aspx’ ,’customListView’ ,800,600);">link name</a>

    5. I did get the function to load correctly, with a few minor tweaks to what I posted, buty I lost the hide functionality. I cant figure out how to pass the ID from the link. I am also going to try it in a modal. any help with the hiding would be appreciated.
      thanx

    6. To have a menu to select list from, do it like this:

      <select id="listViewSelector">
      	<option value="/test/English/Lists/ECBCopyItem/AllItems.aspx">List 1</option>
      	<option value="/test/English/CopyTo/Forms/AllItems.aspx">List 2</option>
      </select>
      <input type="button" value="load" onclick="loadListView()">
      <div id="placeholder"></div>
      
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript">
      
      function loadListView(){
      	var url = $("#listViewSelector").val();	
      	$('#placeholder').html("<iframe id='customListView' src='"+url+"' width='1100px' height='800px'>");
      	$('#customListView').load(function(){
      		hideContents();
      	});
      }
      
      function hideContents(){
      	$('#customListView').contents().find("#LeftNavigationAreaCell").hide();
      	$('#customListView').contents().find(".ms-titlearealeft").parents('tr:first').hide();
      	$('#customListView').contents().find(".ms-globalTitleArea").parents('tr:first').hide();
      	$('#customListView').contents().find("#onetIdTopNavBarContainer").parents('tr:first').hide();
      	$('#customListView').contents().find(".ms-globalbreadcrumb").parents('tbody:first').hide();	
      }
      </script>
      

      Alexander

  233. Good day. You have so much to go through here. I am using sp2010. I have a list with a sum and a few calc columns. when the “Sum=” loads at the top of the page I want to remove “Sum=” and I want to align the value right. looks like sp aligns left, for currency this does not work. Also Do you know details about sum? meaning if there are negative numbers are they subtracted from the total? also if sum is a negative number can a color “red” be applied?

    1. hey Tim, this should give you what you want. I got it from A many moons ago. I left the comments in to help you. This script replaces Sum with Total, but you can leave it blank. You should also be able to apply color. Sum CC’s i know I read a blog long time ago, but it was not perfected. Maybe A can shed some light.
      [sourcecode]
      <script type="text/javascript" src="../../Scripts/jquery-latest.min.js"></script>
      <script type="text/javascript">
      $(document).ready(function() {
      //var aggrText = $(‘TBODY#aggr > tr > td > table > tbody > tr > td > nobr > b’);
      //alert(aggrText.text());
      //alert(aggrText.html());
      var aggrHTML = $(‘TBODY#aggr > tr > td > table > tbody > tr > td > nobr > b’);
      var aggrText = aggrHTML.text();
      var newText = "Total" + aggrText.substring(3);
      aggrHTML.html(newText);

      // know what Total you want
      //var myTotal = whatever;
      //aggrText.html(myTotal);

      // Whatever your text is, that will replace everything inside the <b> tags
      //var newText = "Test";
      //aggrText.html(newText);

      </script>

    2. Tim, the above code is missing the closing
      });
      on line 19

      if you add this it should work in MOSS and 3.0. I have been trying to get it to work in 2010 but not successful

  234. Hi Alexander,

    The question I got would be a modification of one of your cool scripts. I would like to show certain fields on a list item only to the creator of the list item. Is it possible?

    1. Hi,
      Something like this:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript">
      fields = init_fields();
      
      var arrToShowForCreatorOnly = ['OnlyForCreator','AnotherField'];
      
      var createdByID = parseInt($("#onetidinfoblock1").find('a:first').attr('href').split('ID=')[1],10);
      
      if(createdByID!==_spUserId){
      	$.each(arrToShowForCreatorOnly,function(i,fin){
      		$(fields[fin]).hide();
      	});
      }
      
      function init_fields(){
      	var res = {};
      	$("td.ms-formbody").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			$(res[fin]).attr('FieldDispName',disp);
      			$(res[fin]).attr('FieldType',type);
      		}
      	});
      	return res;
      }
      </script>
      

      Note: this example is tested in SP2007 only, if you use SP2010 it might need a little tweak.

      Alexander

  235. I have a search results web part (SP2007) that returns a list of web sites that the user is able to access. Can you offer any tips/code/references for using javascript reformat the list and group by URL into a heirarchy?

  236. Hi Alex,

    I had a site collection with sub-sites underneath it. All sub-sites including Main site collection have a Document Library called “Project Documents”. I need to show up the tree view with sub-sites and only “Project Documents” Library on the Main Page Quick launch Navigation of Site Collection. So user can go directly to that library from default site collection page. I had write this code and i can only get Main site collection Project Document library but not the sub-sites Project Document Library. I am not a Jquery expert i need some help to complete this code.

    I had this jQuery :

    $(document).ready(function()
    {
    // hide all of the tree view elements that are not related to the ‘Project Documents’
    $(“div.quicklaunch-treeview > div > table”).each(function() {
    if( $(this).find(“td.ms-navitem > a:not(:contains(‘Project Documents’))”).is(“a”) ) {
    $(this).css(“display”,”none”)
    }
    });
    // change the value of the site hierarchy heading to ‘Explorer’
    $(“a.quicklaunch-sitehierarchy”).html(“Explorer”);
    });

    Regards,
    Andy

    1. Hi,
      I looked at this, but with multiple levels in the hierarchy it becomes a bit messy – another thing is that this code must be placed in all pages that displays this tree view to work. I recommend you to make some kind of custom menu, but here is something i threw together as a starting point if you want to go the tree view route:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript">
      console.log(WebForm_DoCallback)
      hideAllButProjectDocumentsFromTreeView();
      function hideAllButProjectDocumentsFromTreeView(){
      	$("div.ms-treeviewouter td.ms-navitem").each(function(){
      		console.log($(this).parents('table:first').find("td:eq(1) img").attr('src'));
      		if($(this).parents('table:first').find("td:eq(1) img").attr('src').match('stsicon.gif')!==null){
      			return;
      		}
      		if($(this).find("a[title='Project Documents']").length===0){
      			$(this).parents('table:first').hide();
      		}
      	});
      }
      
      function TreeView_PopulateNode(data, index, node, selectNode, selectImageNode, lineType, text, path, databound, datapath, parentIsLast) {
          if (!data) {
              return;
          }
          var context = new Object();
          context.data = data;
          context.node = node;
          context.selectNode = selectNode;
          context.selectImageNode = selectImageNode;
          context.lineType = lineType;
          context.index = index;
          context.isChecked = "f";
          var tr = WebForm_GetParentByTagName(node, "TR");
          if (tr) {
              var checkbox = tr.getElementsByTagName("INPUT");
              if (checkbox && (checkbox.length > 0)) {
                  for (var i = 0; i < checkbox.length; i++) {
                      if (checkbox[i].type.toLowerCase() == "checkbox") {
                          if (checkbox[i].checked) {
                              context.isChecked = "t";
                          }
                          break;
                      }
                  }
              }
          }
          var param = index + "|" + data.lastIndex + "|" + databound + context.isChecked + parentIsLast + "|" +
              text.length + "|" + text + datapath.length + "|" + datapath + path;
          TreeView_PopulateNodeDoCallBack(context, param);
          // Added
          setTimeout(function(){
        	  hideAllButProjectDocumentsFromTreeView();
          },500);
      }
      
      </script>
      

      The function “TreeView_PopulateNode” is SharePoint’s own.

      Alexander

  237. sorry let me explain further instead of putting out one line staements (gesss I am rude :-)). I know how to hide a button on the ms-toolbar (thanks to you) but the request is now how add another button there, after the cancel or before the cancel button?

  238. Hi Alexander, I am trying to make your “Tabs for Sharepoint Forms”, your “Headings for Sharepoint Forms” and your “SharePoint form: present fields side-by-side” solutions work together, but so far I haven’t been successful.

    If these three worked together I could have total control of the forms page display. Is it possible to make them work together?

    1. Hi,
      These are tricky to get to play together (it’s the “side by side” that is the problem) – I would not recommend it, sorry.

      Alexander

  239. InLineEditing Request:

    Hello Alenxander,

    I’d like to request a version of the InLineEditing script that allows a person field to be a multi select field.

    thanks!

  240. Hi Alexander,

    Thanks for this site, I consider it the #1 End User SP resource on the web.

    I’d like to request a tool / script which could pull the summed total of a column within a list view, then render that value as part of a text string elsewhere on the SP.

    For example if I had a tasks list, and a list-view which filtered the tasks for “open”, with a numeric column – “number of hours” which totaled X. I would like to be able to have a text string on another page, which read “There are X hours of Open Tasks”, etc.

    I have looked at JavaScript solutions such as OWSAPI with a view to coding it myself (badly), though wondered if any of your, more user-friendly/ergonomic, scripts such as the “vLookup type rollup” or the code behind your “Google Chart API” could be adjusted for this purpose?

    Best Regards,

    Tom

    1. Hi,
      Thank you!

      Here is a code example for you:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/spjs_utility - blog/spjs-utility.js"></script>
      <script type="text/javascript">
      
      var argObj = {listName:'PullTotalFromColumn',
      				listBaseUrl:L_Menu_BaseUrl,
      				filterField:'Status',
      				filterValue:'Open',
      				totalColumn:'Cost'};
      
      var myTotal = getTotalFromColumn(argObj);
      alert("myTotal: "+myTotal);
      
      function getTotalFromColumn(arg){
      	var qb, res, total;
      	qb = [];
      	qb.push("<Where>");
      	qb.push("<Eq>");
      	qb.push("<FieldRef Name='"+arg.filterField+"' /><Value Type='Text'>"+arg.filterValue+"</Value>");
      	qb.push("</Eq>");
      	qb.push("</Where>");
      	var res = spjs_QueryItems({listName:arg.listName,listBaseUrl:arg.listBaseUrl,query:qb.join(''),viewFields:[arg.filterField,arg.totalColumn]});
      	total = 0;
      	$.each(res.items,function(i,item){
      		if(item[arg.totalColumn]!==null){
      			total += parseFloat(item[arg.totalColumn]);
      		}
      	});
      	return total;
      }
      </script>
      

      You must go here and fetch the latest version of spjs-utility.js and change the script “src” in the top of the code, and you must edit the “argObj” match your column names and values for “filterField”, “filterValue” and “totalColumn”.

      Alexander

    2. Amazing, thanks Alexander, a Christmas donation is called for!

      I’ve tested your solution and, as per usual, it worked perfectly.

      Unfortunately I’m going to be a pest and add a criteria – can I specify a listview as part of the “argObj”?

      The reason I ask is I’d like to use a specific listview to filter the items by [ME], and all items with a due date in the current quarter, I know how to setup the list views, though not how to reference said view in your code, or adjust the code to achieve the same aims.

      Thanks again,

      Tom

    3. Just as a quick update to the above request: I have been able to add a field to my list and use your original code to filter according to today’s “year-quarter” (e.g. ‘2011-Q4’). I have also used your getUserInfo to retrieve the active user, though am stuck at this next step:

      Can the code you provided be modified to filter **2** separate fields before pulling the total, specifically:
      “YearColumn” = today’s year-quarter <- **complete**
      &
      "Created by" = user <- **stuck**

      Thanks Again,

      Tom

    4. Hi,
      Thank you for the donation!
      Here is an updated code example:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/spjs_utility - blog/spjs-utility.js"></script>
      <script type="text/javascript">
      
      var now = new Date();
      var yq = now.getFullYear()+"-Q"+Math.floor((now.getMonth()/3)+1);
      
      var qb= [];
      	qb.push("<Where>");
      	qb.push("<And>");
      	qb.push("<Eq>");
      	qb.push("<FieldRef Name='YearColumn' /><Value Type='Text'>"+yq+"</Value>");
      	qb.push("</Eq>");
      	qb.push("<Eq>");
      	qb.push("<FieldRef Name='Author' /><Value Type='Integer'><UserID Type='Integer'/></Value>");
      	qb.push("</Eq>");
      	qb.push("</And>");
      	qb.push("</Where>");
      
      var argObj = {listName:'PullTotalFromColumn',
      				listBaseUrl:L_Menu_BaseUrl,
      				query:qb.join(''),
      				totalColumn:'Cost'};
      
      var myTotal = getTotalFromColumn(argObj);
      alert("myTotal: "+myTotal);
      
      function getTotalFromColumn(arg){
      	var qb, res, total;	
      	var res = spjs_QueryItems({listName:arg.listName,listBaseUrl:arg.listBaseUrl,query:arg.query,viewFields:[arg.totalColumn]});
      	total = 0;
      	$.each(res.items,function(i,item){
      		if(item[arg.totalColumn]!==null){
      			total += parseFloat(item[arg.totalColumn]);
      		}
      	});
      	return total;
      }
      </script>
      

      Alexander

  241. Hi,

    I am stuck with a document library form validation issue. I just want to check my document name for white spaces and block the item from saving to the library.

    I am able to do this to a List Library using the below code

    ———————————————————-

    function PreSaveAction()
    {
    var attachment;
    var filename=””;
    var sp=””;
    var file=””;
    var filenamewhitespace = new RegExp(‘\s’, ‘g’);
    try {
    attachment = document.getElementById(“idAttachmentsTable”).getElementsByTagName(“span”)[0].firstChild;
    filename = attachment.data;
    sp = filename.split(‘\’);
    file = sp[sp.length-1];
    }
    catch (e) {
    }
    if (filenamewhitespace.test(file)) {
    alert(“Please remove white space from the file attachment name.”);
    return false;
    }
    else {
    return true;
    }
    }

    ———————————————

    But am not able to do this with a document library, as I dont know how to get the document name to the variable. What should I use instead of — “idAttachmentsTable” —

    Can anybody help?

    BR

    1. Hi,
      I do not think you can make this work for a document library as the “NewForm” does not exist. If you upload a document, you end up in EditForm directly – and the document is “in” before you can validate the name.

      Alexander

  242. Hi again Alex:
    I need to display List items in a modified Box view style in which field names and the data are stacked in 3-4 columns across the page, and 3-4 rows down.
    Example:
    Col 1 Col 2 Col 3 Col 4
    Row 1 field1 field3 field4
    Row 2 field2
    Row 3 field5
    Row 4

    The point here is that the code allow for the placement of fields in a List View in an XY grid. I am just assuming that the Box view is the closest.

    Possible?

    Charlie Epes

    1. If the box view is not quite there, I believe modifying it will be hard and messy. I’m not quite sure what you want to achieve so if you could send me some sketches I might be able to help.

      Alexander

  243. Good day A, Have a question. Is there an easy way to add to the SP 2010 ribbon an approve all button. I hate having to select each item and manually approve each one. I have found some script but they are deployed on central admin. I would like to a void that.

    thanks

    1. Hi,
      Add this code to a CEWP in the view where you want the image to be visible:

      <style type="text/css">
      .itemEditBgImg{
      	background-image:url(/_layouts/images/edititem.gif);
      	background-repeat:no-repeat;
      	background-position:center center;
      }
      </style>
      
      <script type="text/javascript" src="/iPortal/EMSKJS/jquery-1.6.4.min.js"></script>
      <script type="text/javascript">
      if($(".ms-vh-inlineedit").length>0){
      	$(".ms-vb-firstCell").each(function(){
      		$(this).next().addClass('itemEditBgImg');
      	});
      }
      </script>
      

      Alexander

  244. Hi Alex,

    Shot in the dark here:

    You don’t know a way of pulling the current list view name (other than using the URL), and representing it as text in a CEWP above said list, do you?

    I have replaced the view selector with a Superfish Dropdown (thank you btw!) to make it more idiot-proof for my end-users. Though I’d like to add a “View: ” titile bar, to make it even easier to navigate.

    Reason I’m trying – perhaps foolishly – to avoid pulling the name from the URL is because the names will have complex characters, and I don’t want to litter the URL with “%20″s, etc.

    Any thoughts would be appreciated.

    Thanks as ever,

    Tom

    1. Hi,
      This is possible, but I need to know if you are on SP2007 or SP2010.

      You could also unescape the “URL-name” to get rid of the %20’s

      Alexander

    2. Hi,
      Sorry for the late reply, but here you go:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript">
      
      $(document).ready(function(){
      	var view = getCurrentViewName();
      	alert(view);
      });
      
      function getCurrentViewName(){
      	var xmlWrap, result;
      	xmlWrap = [];
      	xmlWrap.push("<?xml version='1.0' encoding='utf-8'?>");
      	xmlWrap.push("<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>");
      	xmlWrap.push("<soap:Body>");
      	xmlWrap.push("<GetView xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>"+ctx.listName+"</listName><viewName>"+ctx.view+"</viewName></GetView>");
      	xmlWrap.push("</soap:Body>");
      	xmlWrap.push("</soap:Envelope>");
      	xmlWrap = xmlWrap.join('');	
      	$.ajax({
      		async:false,
      		type:"POST",
      		url:L_Menu_BaseUrl+'/_vti_bin/views.asmx',
      		contentType:"text/xml; charset=utf-8",
      		processData:false,
      		data:xmlWrap,
      		dataType:"xml",
      		success: function(data){
      			result = $(data).find('View').attr('DisplayName');
      		}
      	});
      	return result;
      }
      </script>
      

      Alexander

    3. Thanks Alex! & sorry for the slow reply!

      I’m quite amazed that nothing seems to stump you.

      Is there anyway to doucment.write() this list view name after the script?

      I would like to format the view name as a title in a CEWP above the list. My initial attempt to use – document.write(view) failed miserably.

      Best Regards,

      Tom

    4. Ignore me, solved it myself (a remarkable achievement given my level of ignorance):

      Replaced:

      alert(view);
      

      With:

      document.getElementById("view").innerHTML = view;
      

      Then added:

      <span id="view"> </span>
      

      Where I wanted the view name to be listed. Works like a charm, Thanks Alex.

  245. hi, I am very big fan of you.
    I have a request for you. I want to redirect to custom page once user click on save from newform.aspx.but it redirect to allitems.aspx.If i write redirect code in Presave action before “true” it redirect but does not save the data.

  246. Hello,
    I am using a group by in a list on sharepoint 2007 and per default that list is collapsed. What piece of code do I add to a CEWP that would open only the top node in the list?
    thanks!
    Michel.

  247. Alexander,

    Can any of your existing solutions be used to display a calculated column in the EditForm.aspx? Is that something that can be done with JavaScript or jQuery?

    Thanks for everything you do for this community!

    1. I should have said more. I would like to display the results of a calculated column in a read only mode in the EditForm.aspx. It would be fine to display the stored value in that field from the saved item version… its doesn’t necessarily have to be dynamic.

      I tried using your field properties dashboard script (Cross-Site Lookup Column?) but that didn’t work for me.

    2. Hi,
      Like this:

      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
      <script type="text/javascript" src="/test/English/Javascript/spjs_utility - blog/spjs-utility.js"></script>
      <script type="text/javascript">
      var myListName = "9BF023FB-B7FE-4B52-B1D7-EDA9B1ED82B0";
      var fieldInternalName = "MyCalculatedColumn";
      var fieldLabel = "My column";
      var fieldToAppendTheRowTo = "Title";
      
      var fields = init_fields_v2();
      var thisItem = spjs_getItemByID({listName:myListName,id:GetUrlKeyValue('ID'),viewFields:['ID',fieldInternalName]});
      $(fields[fieldToAppendTheRowTo]).after("<tr><td class='ms-formlabel'><h3 class='ms-standardheader'>"+fieldLabel+"</h3></td><td class='ms-formbody'>"+thisItem[fieldInternalName].split(';#')[1]+"</td></tr>")
      </script>
      

      You must change the four topmost variables – and you must refer “spjs-utility.js”

      Alexander

    3. Alexander, thanks so much, I didn’t realize you posted a solution! I tried it and found that it has the same issue that I’ve experienced when combining your scripts with the Tabs for Sharepoint Forms solution. Whenever the script has a prepend or append function, the script results apprear on every tab. Do you know how that can be fixed?

    4. Hi,
      What you have to do is to add the newly created <TR> to the “fields object” – try something like this (add this code after the code provided in the above comment):

      fields['MyCustomName'] = $(fields[fieldToAppendTheRowTo]).next();
      

      Now you can use the name “MyCustomName” as any other FieldInternalName in the tabs constructor.

      Alexander

  248. Alexander,
    Using SP2010, I have a need to be able to “schedule” banner images to show on a page. Similar to an Announcements schedule, but with images only. I envision having a list with the image URL and start/stop dates to pull from. Any ideas?

    1. I guess you could use a custom list with an image field – and have a start and end date to filter the view by? Then you add this list – with only the image field visible to your page.

      Alexander

  249. Hi Alexander,

    a colleague of mine came up with a request for a sharepoint list today. He’s tired of using an excel spreadsheet for email distribution lists and wanted a sharepoint solution from me that’s ‘three year old’ safe. Importing contacts from e.g. Outlook is not an option (since we don’t use Outlook). My first idea was that it should be pretty simple, just set up a list, define “to”, “cc”, “bcc” fields, a “name” and “subject” field and put it all together with a calculated field to generate a “mailto:” clickable field within a list (preferably using the distribution list name as the identifier).

    So far so good but of course having only 255 characters for a single line field is not enough (and it’s not really usable to enter/edit data), having several of them not an option. So I altered my idea to have “to”, “cc” and “bcc” fields as plain text multiline fields but surprise surprise, those can not be used in a calculated field.

    So I’m back to start and after spending some two hours with google rather clueless on how to set up such a list. Most of the search results refer to importing lists from Outlook, AD or another source which is not possible here. I’ve had a look at your solution to combine several single line fields into one multiline field but that didn’t help either.

    Can you think of a solution to have multiline edit fields for the names that can be concatenated to use a calculated “mailto” clickable link?

    Chris

  250. Hello Alexander,

    I would like to get to the add attachments box for an item in a list without clicking “edit” first, followed by “attach file”. I have learned that in the editform.aspx, the attachment box is hidden per default. Is there a way to open the editform.aspx and show the attachment box without that extra click?

    I am using your “inline editing script” and also your “mouseover paperclip” script to view attachments in a list view. Now the last part to turn my page into a truly friendly UI is to be able to add an attachment to a list item directly from the list view.

    thanks for considering my request !

    Michel.

    1. I’ll put this one on the list of things to do. I do have a few other script updates for some of my existing solution to attend to before I can look at it, but stay tuned.

      Alexander

  251. I subscribe at Michels request, great idea,also for 2010.. Also if we can get a solution for attachments history without storing them in a separate document library. 😉

    If I can do more instead of subscribuing here…let me test it

    Regards
    Michael

  252. Back again, now using WordPress account:

    I am looking for an idea how to copy a list item into a new item (preferred) at the same list. In other words:
    Select ID x by mouse (left/right), choose copy item, select a list (out of this site collection), click to copy, done…ID yy is created with all fields like ID x (dont take care for last modified, user,… only interested to copy the metadata belonging to the item itself)

    Root cause for this is that when using list a history with versions did not a correct versioning for attachments from the list item

    Thanks, Alex.

    Warmest regards
    Michael

    1. It’s no problem to copy a list item by adding an entry to the ECB menu (the dropdown on the tilte field), but it’s not possible to copy the attachment in this process.

      Alexander

    2. Michael Again 🙂 Long night today:)

      I know that this unusable to copy the attachment, but to copy the list item into a new one, adding with the next step a new(er) version of the same attachment (as used before) and set it to “valid” by a common checkbox in the list. The source list item also then will be set to “invalid” and greyed (filtered) out from the list.

      Also this allow me to work with the brandnew offline client we decided to use (and is not so much confusing as storing the attachments in a separat doclib)
      Regards
      Michael

    3. One more explanation why we can not add the new attachment to the same item: We need to show which attachment version (usually containing some rules) was valid at which time window. New version of rules = new version of attachment = new valid entry and one new “invalid” (the older one) entry. And copying the items avoid typing of repetitive metadata stories 🙂

    4. No,
      That code example is server side code. I’ll add this to the “to-do-list”, but I have little time to spare for the time being so I cannot say when I’ll get the time to post it.

      Alexander

    1. Work phone is not part of WSS3.0 and therefore I have not added it. You can however add as many fields as you like to the array of fields in the function.

      Alexander

    1. Your code is something that I may be able to use elsewhere but not for this and the reasons are Alexander has offered to fix his and I have already created the custom list will all my entries for it.

      I am however on time constraints and depending on how quickly he has a new version dictates what I will be doing.

      Lastly, your page isn’t complete as I cannot see all the coding….

  253. Alexander,
    First, MAD PROPS to your crazy good skills! Secondly, I need to create a compact news previewer exactly like this: http://tympanus.net/codrops/2010/10/03/compact-news-previewer/, but the input needs to be from a BLOG. I’d like the preview to show the top 5 approved and published news articles (blog posts), for instance, and display the Rollup Image, Title and Excerpt. Ideally, I’d also like it to auto-cycle through each of the 5 displayed, at whatever interval I set. I see many, many uses for something like this, whether it be from a blog, list, asset library, or whatever. PLEASE HELP!! Oh guru of the jQuery world, I bow to your knowledge and direction! And for a solution, a couple rounds of beers on me! I look forward to hearing from you.

  254. Alexander,

    I have a request that involves the People Picker in SharePoint 2007. The OOTB solution only allows us to choose “People only or People & Groups”. Is there a way to have it only allow for “Groups only”?

    Thank you for all that you do!

    1. Oh, another thing. Would it be possible to limit the amount of groups that can be selected per field? I am already using your spjs-utility to validate the data in 2 pickers to verify that they both don’t contain the same single group…

    2. Hi,
      Sorry, but i do not have capacity at the moment to take on new development. I have a few scripts in this blog that addresses people pickers. Look at them and see if you can use bits of the code.

      Alexander

  255. Hey Alexander and others,
    I hope I am not double-posting here, but my request has to do with the excellent scripting done already on “Preview Metadata” in regards to a Sharepoint 2007 site. I have a list view that i am using this with and it works great. What I would like to do however is rather than use the Jquery hover event to bring up the popup, I would like to make the popup a “dialogue” event that is activated on a click and dismissed with a click. So it is a new request, but based on an old and awesome script. What do you think?

  256. Hi Alexander,

    I’m trying to send an email to a list of email addresses using the Server’s default outgoing email as the sender. The email addresses are in one single column.
    Basically the list is a “Enter Your Email to Subscribe” list and when a new announcement of feature is added, I can then send an email to all email addresses in the list.
    I don’t have User Profile Sync set up, so I can’t use the email address from User Profiles.
    I’ve found this: http://social.msdn.microsoft.com/Forums/en-HK/sharepoint2010general/thread/0a760ab8-dfad-4880-acb4-15a7a0055283 where the person at the bottom explains how to do it using Javascript but doesn’t provide the actual code. 🙁

    If you can find some time to provide a script, I’ll send a few beers your way?

    1. Hi Alexander,
      I haven’t found a solution for this other than physically adding a user to a SharePoint group and using a workflow.
      If you get time and if it can be done, that would be great, no hurry.
      ,
      Brett

  257. Hey A, it’s been a while. I hope you are well. I amnot really sure what I need, but anm hoping you can point me in a direction. I want to get a facebook rss feed to display in sharepoint. I tried using the default rss reader, but I get an error for facebook. do you know how this can be done or a work around?
    Larry

    1. Hi Larry, I’m afraid I cannot help you with this. I’m not on Facebook so i have no knowledge about their RSS feed. Alexander

  258. Hi Alexander,

    I have a request – I have apx 250 managers who all need to faciliate a meeting where they collect different data on employees. I’ve made a summary sheet in Excel for them.

    But I would love for them to be able upload the data directly to SharePoint, so all the data is collected in one huge list for me to dissect and summarize. From what I’ve red in forums the import function is lacking in SharePoint 2007 (and 2010).

    The alternative to the solution above is they all upload their file to a library, for me to do all the work in Excel and the c/p into SharePoint… 🙁

    Really hope you would consider to provide a solution to this common SharePoint problem, which it seems to be. 🙂

    Thanks for all your great blogs.

  259. Hi Alexander, I’m loving your double booking resource check script but was wondering … I’d like to use it to manage our training rooms of which they are circa 80. Short of the scheduling staff trying several times to find a free room I was wondering whether there is any additional script that would show the availability of rooms. That way the team can look and see what isn’t booked and go ahead. If by that point someone else has booked the room, your current script will stop the double booking.

    Not to worry if not I’m just keen to move away from a massive colour coded spreadsheet :/

  260. Dear Alexander,

    We’d like to add a dotted line to the solid line graph where dotted would represent forecast while solid are actuals. Any suggestion on how this can be done? We’re still on API 2.7 SP Control Update.

    thanks
    Clare

  261. Hello,

    I read through most of your posts Alex. You have some great Javascripts. I have a couple of questions, if you can please help me answer them would be great.

    1. I need to attach Javascript to a custom EditForm for a content type, so I did it the traditional way, i.e. attach Javascript to the CEWP. But everytime I create a template of the document library when this form is residing, it drops the CEWP. My question is that you mentioned that Javascript can be attached inline, i.e. can we reference it in the custom EditForm.aspx code somehow? Please note that the Javascript is working great on the current document library. Also, when we create the template, the custom EditForm is getting copied over, it is just dropping the CEWP. Please advice.

    2.For the OOTB Calendar, I have added it on a page using webpart. Now, I wish to make some changes to it. For instance, change the days of the week to display 3 letter acronymn, and not just a single letter. Also move the prev/next images. I wrote a Javascript to scan the HTML and am trying to replace Sunday, would this work?

    Again thanks much for all your help.

  262. Hi Alex:
    Just like your fantastic “First/Today/Last” date picker solution does, is it possible to add a “Today” clicker on top of a Single line of text or Multiple lines of text so that an entry can have today’s date + semicolon + a space? I know that versioning will do this but I need users to have freedom to edit. Thanks- Charlie Epes

  263. Hello Alexander,
    Thank you for the great tips and codes you provide regularly here!!!

    I’m using SharePoint Online (O365), and I have lists and libraries with huge amount of views. I would like to organize the views (they’re just presented today in alphabetical order) in the list or library views dropdown. I’d like to have a menu/submenu presentation with specific labels for the grouping of elements. Could you help?
    Thanks a lot (even if you can’t ^^).

  264. Hey A, Hope you are well. quick question. Is there a way to disable all links on a calendar. I have a publishing site, which in itself is a nightmare. I want to display the calendar, but i dont want the user clicking any links because they will be authenticated. if I disable the links that will giove them results. I have tried several methods
    [sourcecode 1=”$("td.ms-cal-topday” 2=”div” 3=”a").attr("href","javascript:void(0);")” 4=”[/sourcecode” language=”}”]
    [sourcecode}
    $("td.ms-cal-topday div a").removeAttr("href")

    I an see the attribute removed, but the link still works.

    thanks Larry

    1. lost the source code

      [sourcecode]
      $("td.ms-cal-topday div a").attr("href","javascript:void(0);")

      [sourcecode]
      $("td.ms-cal-topday div a").removeAttr("href");

  265. Hello Alexander,

    I while ago your posted a solution to hide the “Sum=” prefix from the Total columns.

    I’ve placed your code in a CWP that’s below the list but nothing happens. The list is placed on a sitepage with a graph webpart.

    What can be the problem?

    Thanks in advance,

    Jimmy

    1. IE Dev Tools can be your friend. Sometimes I have similar issues. This tool help you to identiy the correct elements. Once identified you can update your script or css.
      what version of SP or you trying this on?

    2. Hi Larry,

      You’re right, i’ve managed to solve the problem. In my case if was the translation to Dutch that did the trick.

      Thanks for your reply.

  266. Hey A,
    I have searched for this now over several days and i cannot find a solution. Not that I want you to build one, I just want to know if it is possible. I want to display a 2 month calender view. I am ok with added to separate calendar web parts, I just want the second one to always display next month.

    Using list view this is easy to accomplish, but I cannot figure out a solution for a calendar view.
    any suggestions?
    thanks

  267. Thanks Alexander for your contribution. This was relatively easy to implement even for a beginner like me.
    I was wondering if you could post an example of a chart using the select event ‘getSelection()’ to link a portion of the chart back to a subset / filtered data in the SharePoint list?
    Thanks.

  268. Is there a solution to pull in the names of selected people as part of a “people or group” field into another field vertically stacked? I’ve tried using a calculated field but the “people or group” field type doesnt seem to be supported. Any help would be greatly appreciated. Thanks.

  269. Infamous fields-side-by side…

    Has anyone overcome the issue of mulitple fields in one ? Changing the positioning of the script above or below the get/set field script does change the behavior, but does not get it to work.

    Last comment on it a year or so ago was basically ‘don’t try it’. Perhaps there is an alternative way to get the same look?

    Brian

  270. Hi Alexander, hope you are doing well. I am still enjoying your solutions on our internal pages.

    But today, I want to ask for new solution (or a link to a similiar solution).

    How to add TABS to sharepoint pages which uses individual links (url from www, another view of the same list, jumping to a doclib, home button,…..), shown on top of page, must not be part of the ribbon (because this did not appear easily after adding webparts)

    Searching around I can only find your tabs for fields or the easy tab solution, but no solutions which add the tabs with jquery and take the links from a list or out of the code…
    A list (an ID out of a list) looks preferrable, because it can reused at several locations to provide links.

    Any Ideas or Hints?

    Kind regards
    Michael

  271. Alexander,
    Like everyone I find your scripts extremely useful and i thank you for them. I have what i hope is a simple question: using the truncatetextinlistview Is there a way to dictate how wide the popup is going to be? i basically need it to appear to the left of the mouse button instead of the right and use most of the page…
    v/r
    Rob

  272. Hey again A, Hope you are well. I am looking for a quick solution and have been unsuccessful. I have a web part page. The page I am using has the header and footer with 3 columns. I am trying to set/force a width, at least to the outside columns and have the middle one take up the rest. I know if I fumble with it enough I can make it work on that one page. but I am looking to create a way that no matter which page I drop it on, maybe all I need to do is define the column widths. several of the styles I have tried have failed. setting the width of the web part failed. I still have this white space I cant get rid of. so I think my issue is I am not targeting the correct element. can you shed any light on this?

    1. Hi Larry,
      We discussed this by email, but I wanted to put the answer here for others to see.

      Hi,
      Try inserting a CEWP in the left web part zone with a div like this:

      <div id="leftColumn"></div>

      Then use this code to fix the width:

      $("#leftColumn").parents("#_invisibleIfEmpty:first").css({"width":"10%"}).next().css({"width":"80%"}).next().css({"width":"10%"});

      Alexander

  273. good day, I am seeking a way to disable or remove links from a calendar view on SP 2010. when I view the source I do not see any anchors or hrefs. How are the links created, and can they be removed or disabled?

    1. Sam,
      I took a look at this and I was kind of befuddled. I did identify that the days are on a clickable div and I was able to disable them, but if I navigated to another month I lost that function. I also noticed that the events appear to be place on the calendar using a content area. I was not able to see the details in the source code. you can look at what I have it might help you along. Perhaps A can solve this better for you.

        
           if(typeof jQuery=="undefined"){  
               var jQsrc="/Scripts/jquery-1.9.1.min.js";
               document.write(unescape("%3Cscript src='"+jQsrc+"' type='text/javascript'%3E%3C/script%3E")); 
           }  
      
      
      
      $(document).ready(function(){ 
      		$(".ms-acal-rootdiv div").click(function() {return false;});
      
      });
      
      
    2. Hi,
      Is it the “title” linking to the item you want to remove? If so, try this code:

      <!-- refer jQuery -->
      <script type="text/javascript">
      setInterval(function(){
      	$(".ms-acal-sdiv a").each(function(){
      		var text = $(this).text();
      		$(this).before(text);
      		$(this).remove();
      	});
      },500);
      </script>

      This code fires every 500ms and replaces all anchor tags with their text value.

      Edit: the code disappeared.

      Alexander

  274. Would the resize multi line text field javascript work in conjunction with the Dynamic Forms script? Or is it possible to institute that feature within the dynamic forms script.

    Thanks…

  275. Good day, I am inquiring if there is a way to sort attachments. I understand the are added into a table, or row. Can jquery have the ability to sort them? and if they can be sorted can they be sort by user selected order?

    thanks

  276. hey A,
    You know I love your site, blog, posts. It is great that you utilize sharepoint beyond its intended purpose. I have been trying to create a solution that combines several different functionalities, not necessarily from your scripts, but willing to bet you can do this. I am looking to create a text animation. I have read that the marquee is coming back with css3. I have also found that jquery can do some simple animation with the marquee, but I am looking to take it a step or two further.

    I want to use a list. I want to control the number of loops. I want to step thru each item on the list and when I pull an item I want the ability to display it on multiple lines
    example:

    Your
    guide to
    SharePoint

    I would also like the ability to control the speed of each line.
    I have seen your text scroller, So I know most of this can be accomplished. the tougher stuff like multiple lines and speed for each line, much tougher. I am not sure if maybe the source list has several columns for each line or if it could be done with an array. I would be willing to pay for this solution. or maybe you can shoot me some ideas and I can try and hack it.
    thanks Larry

      1. I have emailed this cause the code didn’t come thru. One last thing I did nto mention is for each “LI” the $(“#welcome”).animateText([]} will need to be built, which I am thinking is easy compared to the rest.
        let me know if I have asked for too much

  277. Hi Alex:
    I hope you had a good summer!

    I am trying to freeze list view column headers so the headers stay on the page as the user scrolls down the list.

    There are many solutions posted on the web but none seem to work on a list view. They work on a master page.

    Do you have a simple solution?

    Thanks as always.

    Charlie Epes
    Buffalo, NY

    1. Hi,
      I have tried to do this earlier, but did not find a good cross browse solution so I’m afraid I do not have a simple solution to this. If I remember correctly, I did set the “tr” to position:absolute, and had a script correct for the scroll, but it worked for IE only.

      Alexander

  278. Hi,

    First of all Thanks for your contribution and support. I have a project in which i need to copy data from one list on one site to another list on another site. The Data stored in list1 is dynamic and hence should be moved to another site at regular intervals(Every 30 secs).List1 contains colums like issues , assignedto, and status and list 2 contains columns with assignedto and status but list 2 will give a count of how many issues are assigned to associates.
    something like this
    List1
    Issues Assignedto Status
    Issue1 cari Assigned
    Issue2 Terri New
    Issue3 cari Assigned
    Issue4 Teri Assigned

    List 2 should contain
    Assignedto Status Count
    cari Assigned 2
    Terri Assigned 1
    Terri New1

    Chalenges are

    1)These 2 list are on different sites (Reason being the client does not want to touch the original list)
    2)Getting data accross sites
    3)the List1 data has to be synchronized with list 2 to every second(data has to be refereshed with few sec)
    4) the count calculation has to be done before the data is between copying data from list1 and putting the count in list 2

    Kindly help.

    4)

  279. Hey Alex, it’s been a while. I have a small request for you. I have been struggleing with this for over a day. I want to load a sp 2010 page and hide all navigation and quicklaunch, but I want to ability to show this if I am an admin or editor of the page. Now using these styles I can hide all I want;

    #s4-ribbonrow, 
    .ms-cui-topBar2, 
    .s4-notdlg, 
    .s4-pr s4-ribbonrowhidetitle, 
    .s4-notdlg noindex, 
    #ms-cui-ribbonTopBars, 
    #s4-titlerow, 
    #s4-pr s4-notdlg s4-titlerowhidetitle, 
    #s4-leftpanel-content {display:none !important;}
    .s4-ca{
    	margin-left:0px !important; 
    	margin-right:0px !important;
    	}
    

    but I cant not get it to display when I want to view it. I have tried switching stylesheets, but not effective for round trip. I have tried using just jquery, but toggle doesnt leave me the desired effect I am looking for. and ultimately I would like to have a cookie so it remembers my choice.

    can you help with this?
    thanx
    Larry

    1. Whew, ok, I have a some what working solution, missing the cookie.
      here are my styles

      .hideme {
      	display:none !important;
      }
      .marginremove {
      	margin-left:0px !important; 
      	margin-right:0px !important;
      }
      #admin {
      	text-align:right;
      	margin-right:20px;
      }
      #admin:hover {
      	cursor:pointer;
      }
      

      jquery: include jquery reference:

      $(document).ready(function() { 
      
        $("#admin").click(function(){
          $("#s4-ribbonrow").toggleClass("hideme");
          $(".ms-cui-topBar2").toggleClass("hideme");
      	$(".s4-notdlg").toggleClass("hideme");
      	$(".s4-pr s4-ribbonrowhidetitle").toggleClass("hideme");
      	$(".s4-notdlg noindex").toggleClass("hideme");
      	$("#ms-cui-ribbonTopBars").toggleClass("hideme");
      	//$("#s4-titlerow").toggleClass("hideme");
      	$("#s4-pr s4-notdlg s4-titlerowhidetitle").toggleClass("hideme");
      	$("#s4-leftpanel-content").toggleClass("hideme");
      	$(".s4-ca").toggleClass("marginremove");
        });
      });
      

      then I add to the page

      
       					Admin
      				
      

      besides a little formatting the toggle works. I need to default it to hide, and I wand to add cookies to remember, from page to page. con you help me with this?

      thanks
      larry

      1. Sorry for the delay, but I have had a lot of emails to go trough.

        Some of the code was removed. You must wrap it in
        <code>
        // Code here
        </code>

        Alexander

    2. Thanx A, I was able to figure this out. I realized I only needed to set the cookie for the Admin, leave it blank other wise. IF anyone is interested in the code I can share it.

  280. So again I have a new request. I am looking for a straight stick countdown timer. Basically days hours minutes and seconds. I need to be able to apply css to format each individually. I would also like a progress bar showing the relative remaining intervals. I already have a working solution for this, but I cannot get it to work in MOSS. I modified the example from here: http://keith-wood.name/countdown.html. I was able to modify this code to add custom style and a progress bar. it doesnt matter how I try to load the content on a SP page, no counter displays. I know it is in MOSS, can you help any? I can provide you my code if it helps.

    thanks Larry

  281. Hello my friend. I have a new request. The recent others I was finally able to resolve. This one is related to color coding a calendar. I have used Christohpe’s script for many years and push it to it’s limits. Onee thing I have noticed, that I cant find a solution for is the title attribut for the individual events. when you show a calculated column in a calendar view it uses that field for the title attribute. So HTML comes across. I want to know how, maybe with jquery, can I replace the title attribute with another field, or a concat of fields so it is just test. Maybe even replace the attribute value with the default Description field.

    what do you think?
    Thanx Larry

  282. Hi Alexander

    I have just come across your blog and can see you have done some amazing work with customising SharePoint.

    Would you know of a method for displaying a column that can display the difference between todays date and the date from column called due, so if it was Monday and the due date was Friday it would display 4days and if it was due last friday then it would display -3days. I would then like to have another column that shows a status colour so it would be green if the were more than 1 day difference, yellow if it was 1 day difference and red if it was into the minus days.

    Happy to pay you for your help.

  283. Everyone loves what you guys are up too. This kind of clever work and exposure!
    Keep up the fantastic works guys I’ve added you guys to my own blogroll.

  284. Hi Alexander, It has been a while and I hope you are well. I am working on trying to figure out how to color code gantt bars in SP 2010. Have you worked with this, and can it be done?

    thanks Larry

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.