1,804 articles and 15,408 comments as of Monday, December 27th, 2010

Monday, April 20, 2009

JQuery for Everyone: Pre-populate Form Fields

Power Users often request the ability to pre-populate form fields. The most straight-forward approach involves passing form field values in the URL as a query string. A while ago, the SharePoint Designer bloggers posted a solution with POJ (plain old JavaScript). Since I’m on a roll, I figured it was time to update this script with some jQuery goodness.

Why This Works Better

This script requires no configuration. Drop it on the page and start passing query string values to the form. The original script required configuration to make it work with specific form fields.

What Kind of Data

So far, I’ve tested this with Text, Rich Text, Numbers, Dates, Date/Time, People, and Choice/Lookup. If you have a test that doesn’t work, please comment this thread.

But Browser Differences Will Break It, Right?

Again, I’ve tested and accounted for the variance in displays of FF3 and IE7. Date/Time and People are the main bad guys since FF3 is told to ignore the picker controls.

How Do We Use It?

First, copy the code and put it in a Content Editor Web Part on your form. Since most forms don’t allow the Edit mode naturally, I’ve kept the URL string you need in the first comment of the code.

Next, start adding to the URL (before the first parameter use ?, subsequent parameters all use & before them), for example:

  • Data Type:Text, string:Title=abc123, examples:
    • http://servername/site/Lists/listname/NewForm.aspx?Title=abc123
    • http://servername/site/Lists/listname/EditForm.aspx?ID=1&Title=abc123
    • http://servername/site/Lists/listname/EditForm.aspx?ID=1&Description=<b>bold text</b>
  • Data Type:Date, string:Due Date=1/1/2010, examples:
    • http://servername/site/Lists/listname/NewForm.aspx?Due Date=1/1/2010
    • http://servername/site/Lists/listname/NewForm.aspx?Due Date=1.1.2010
    • http://servername/site/Lists/listname/NewForm.aspx?Due%20Date=1-1-2010
  • Data Type:Date/Time, string:Start Date=1/1/2010 10:30 pm, examples:
  • Note: Because the interface uses a drop-down in 5 min increments, you must pass a time ending in 0 or 5.
    • http://servername/site/Lists/listname/NewForm.aspx?Due Date=1/1/2010 1:30 PM
    • http://servername/site/Lists/listname/NewForm.aspx?Due Date=1.1.2010 01:30 AM
    • http://servername/site/Lists/listname/NewForm.aspx?Due%20Date=1-1-2010%2010:30 pm
  • Data Type:Radio/Checkbox, string:MyChoice=1, examples:
    • http://servername/site/Lists/listname/NewForm.aspx?MyChoice=true
    • http://servername/site/Lists/listname/NewForm.aspx?MyChoice=TRUE
    • http://servername/site/Lists/listname/NewForm.aspx?MyChoice=1
    • http://servername/site/Lists/listname/NewForm.aspx?MyChoice=0
    • http://servername/site/Lists/listname/NewForm.aspx?MyChoice=false
    • http://servername/site/Lists/listname/NewForm.aspx?MyChoice=FALSE
  • Data Type:Lookup/Select, string:MySelect=@1, examples:
  • Note: You can use either the ID value or the text value. In a single select control, using the text will select the first match.
    • http://servername/site/Lists/listname/NewForm.aspx?MySelect=@1
    • http://servername/site/Lists/listname/NewForm.aspx?MySelect=Text for ID1
  • Data Type:Multi-select Lookup/Select, string:MySelect=abc123,@1,abc,@2 examples:
  • Note: You can use either the ID value or the text value. Text parameters can match multiple options. Separate options by comma.
    • http://servername/site/Lists/listname/NewForm.aspx?MySelect=a,b,c
    • http://servername/site/Lists/listname/EditForm.aspx?ID=1&MySelect=@1,@2,@3
    • http://servername/site/Lists/listname/EditForm.aspx?ID=1&MySelect=@1,@2,@3,a,b,c
  • Data Type:People-Picker, string:Assigned To=pgrenier, examples:
  • Note: Previous versions of a prepopulate script could not populate multiple people-picker controls because they have the same title, “People Picker,” however this script works with the column title.
    • http://servername/site/Lists/listname/NewForm.aspx?Assigned To=SP\pgrenier
    • http://servername/site/Lists/listname/EditForm.aspx?ID=1&Assigned%20To=pgrenier
<script type="text/javascript">
//?PageView=Shared&ToolPaneView=2
if(typeof jQuery=="undefined"){
	var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/";
	document.write("<script src='",jQPath,"jquery.min.js' type='text/javascript'><\/script>");
}
</script>
<script type="text/javascript">
/*
 * Prepopulate form fields in SharePoint
 * Copyright (c) 2008 Paul Grenier (endusersharepoint.com)
 * Licensed under the MIT (MIT-LICENSE.txt)
 */
(function(){
	var params = window.location.search.substring(1).split("&"),
		kv = {},
		opts,
		sp=/%20|\+/g,
		datetime=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d\s([0-1][0-2]|[0-9]):([0-9]{2})\s(A|P)M/i,
		date=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d/,
		clean = function(str){
			return str.replace(sp," ");
		},
		getKv = function(){
			$.each(params,function(i,e){
				var p=e.split("=");
				kv[p[0]]=decodeURIComponent(p[1]);
			});
			return kv;
		};
	jQuery.prepop = function(){
		$.each(getKv(),function(k,v){
			k=clean(k);
			v=clean(v);
			var f=$("[title='"+k+"']"),
				job;
			if (f.length>0){
				if (f[0].type=="text"){job=10;} //text
				if (f[0].type=="checkbox"){job=20;} //checkbox
				if (f[0].tagName=="SPAN"&&f.hasClass("ms-RadioText")){job=30;} //radio
				if (f[0].type=="select-one"&&f[0].tagName=="SELECT"){job=10;} //choice and non-IE lookup
				if (f[0].tagName=="TEXTAREA"){job=10;} //textarea
				if (f[0].type=="text"&&f[0].opt=="_Select"){job=70;} //IE lookup
				if (v.match(date)){job=40;} //date
				if (v.match(datetime)){job=50;} //datetime
			}
			if (f.length===0){
				var elm = $("nobr:contains('"+k+"')");
				if (elm.length>0){
					elm = elm.parents("td").next()[0];
					var s1 = $(elm).find("select:first"),
						s2 = $(elm).find("select:last"),
						p1 = $(elm).find("textarea[title='People Picker']"),
						p2 = $(elm).find("div[title='People Picker']"),
						vals = v.split(",");
					if (s1.length>0){job=80;} //multi-select
					if (p1.length>0){job=90;} //people picker
				}
			}
			switch (job){
			case 10:
				if (v.substring(0,1)=="@"){
					opts = f[0].options;
					$.each(opts,function(i,e){
						if (opts[i].value==v.substring(1)){f[0].selectedIndex=i;}
					});
				}else{
					f.val(v);
				}
				break;
			case 20:
				if (v.toUpperCase()=="TRUE"||v=="1"){f[0].checked=true;}
				if (v.toUpperCase()=="FALSE"||v=="0"){f[0].checked=false;}
				break;
			case 30:
				if (v.toUpperCase()=="TRUE"||v=="1"){f.find("input:radio").click();}
				break;
			case 40:
				v=v.replace(/[\-\/.]/g,"/");
				f.val(v);
				break;
			case 50:
				var dt=v.split(" "),
					d=dt[0].replace(/[\-\/.]/g,"/"),
					t=dt[1],
					hm=t.split(":"),
					hh=hm[0].replace(/^0/,""),
					mm=hm[1],
					ap=dt[2].toUpperCase();
				f.val(d);
				f.parent("td").siblings("td.ms-dttimeinput")
					.find("select:first").val(hh+" "+ap)
					.parent("td").find("select:last").val(mm);
				break;
			case 70:
				if (v.substring(0,1)=="@"){
					ShowDropdown(f[0].id);
					opts = $("#_Select")[0].options;
					$.each(opts,function(i,e){
						if (opts[i].value==v.substring(1)){$("#_Select")[0].selectedIndex=i;}
					});
					f.blur();
				}else{
					f.val(v);
					ShowDropdown(f[0].id);
					f.blur();
				}
				break;
			case 80:
				opts = s1[0].options;
				$.each(vals,function(i,e){
					var V=e;
					$.each(opts,function(i,e){
						if (opts[i].text==V){
							s2.append("<option value='"+opts[i].value+"'>"+V+"</option>");
						}
						if (V.substring(0,1)=="@"){
							if (opts[i].value==V.substring(1)){
								s2.append("<option value='"+V+"'>"+opts[i].text+"</option>");
							}
						}
					});
				});
				break;
			case 90:
				var p=vals.join(";");
				p1.val(p);
				p2.html(p);
				break;
			//default:
			}
		});
	};
})();
$(function(){
	$.prepop();
});
</script>
View all entries in this series: PaulGrenier-JQuery for Everyone»
Entries in this series:
  1. JQuery for Everyone: Accordion Left Nav
  2. JQuery for Everyone: Print (Any) Web Part
  3. JQuery for Everyone: HTML Calculated Column
  4. JQuery for Everyone: Dressing-up Links Pt1
  5. JQuery for Everyone: Dressing-up Links Pt2
  6. JQuery for Everyone: Dressing-up Links Pt3
  7. JQuery for Everyone: Cleaning Windows Pt1
  8. JQuery for Everyone: Cleaning Windows Pt2
  9. JQuery for Everyone: Fixing the Gantt View
  10. JQuery for Everyone: Dynamically Sizing Excel Web Parts
  11. JQuery for Everyone: Manually Resizing Web Parts
  12. JQuery for Everyone: Total Calculated Columns
  13. JQuery for Everyone: Total of Time Differences
  14. JQuery for Everyone: Fixing Configured Web Part Height
  15. JQuery for Everyone: Expand/Collapse All Groups
  16. JQuery for Everyone: Preview Pane for Multiple Lists
  17. JQuery for Everyone: Preview Pane for Calendar View
  18. JQuery for Everyone: Degrading Dynamic Script Loader
  19. JQuery for Everyone: Force Checkout
  20. JQuery for Everyone: Replacing [Today]
  21. JQuery for Everyone: Whether They Want It Or Not
  22. JQuery for Everyone: Linking the Attachment Icon
  23. JQuery for Everyone: Aspect-Oriented Programming with jQuery
  24. JQuery for Everyone: AOP in Action - loadTip Gone Wild
  25. JQuery for Everyone: Wiki Outbound Links
  26. JQuery for Everyone: Collapse Text in List View
  27. JQuery for Everyone: AOP in Action - Clone List Header
  28. JQuery for Everyone: $.grep and calcHTML Revisited
  29. JQuery for Everyone: Evolution of the Preview
  30. JQuery for Everyone: Create a Client-Side Object Model
  31. JQuery for Everyone: Print (Any) Web Part(s) Plugin
  32. JQuery for Everyone: Minimal AOP and Elegant Modularity
  33. JQuery for Everyone: Cookies and Plugins
  34. JQuery for Everyone: Live Events vs. AOP
  35. JQuery for Everyone: Live Preview Pane
  36. JQuery for Everyone: Pre-populate Form Fields
  37. JQuery for Everyone: Get XML List Data with OWSSVR.DLL (RPC)
  38. Use Firebug in IE
  39. JQuery for Everyone: Extending OWS API for Calculated Columns
  40. JQuery for Everyone: Accordion Left-nav with Cookies Speed Test
  41. JQuery for Everyone: Email a List of People with OWS
  42. JQuery for Everyone: Faster than Document.Ready
  43. jQuery for Everyone: Collapse or Prepopulate Form Fields
  44. jQuery for Everyone: Hourly Summary Web Part
  45. jQuery for Everyone: "Read More..." On a Blog Site
  46. jQuery for Everyone: Slick Speed Test
  47. jQuery for Everyone: The SharePoint Game Changer
  48. JQuery For Everyone: Live LoadTip
 

Please Join the Discussion

72 Responses to “JQuery for Everyone: Pre-populate Form Fields”
  1. Mike O says:

    I did see that, but I can’t get it working. At least I’ve been pointed in the right direction. Thank you.

  2. Eric R says:

    This is a great little script that has much possibility for extension. I used this as a base to dynamically capture form values of OTB Fields and custom fields with very uniqe rendering templates! Great job

    • John says:

      Hi Eric,
      Am new to MOSS 2007, i have a requirement like ” i have a survey with three fileds,
      ID/Number field, TItle field, Name.

      In a survey my requirement is when the ID field is selected , the remaining two fields have to be pre populated automatically from pulling hte information from other list.
      IS that possible with OOTB , am sure can’t be. IF with Designer, in which form should i use the script and how do i do that.
      KInldy respond back soon on my email. Thanks a million in advance.

  3. JohnM says:

    Terrific piece of work Paul.

    In the case of the People Picker, is it possible in the script to simulate a crtl-K keypress following the population of the text box in order to execue the check name ?

  4. Sam says:

    Can this script be used to pre populate a table structure, say with 2 rows and 2 columns in a rich text box?

  5. Julie says:

    I so luv you lol

    This really simple solution has enabled me to use one feedback form across an entire site collection to collect feedback from 45 pages and automatically know what page they are feedbacking on without them having to fill in the ‘page commenting on’ ….

    I am going to go one step further and hide the field from the newitem form so they don’t even know they are filling it in automatically …

    How cool is this code! ;-)

    Thanks

  6. Andrew says:

    Hi,

    I have managed to get this script to pre-populate a text field in a survey in SharePoint Server 2007, but would also like to populate another field – a multiple choice with drop-down menu and also ‘Fill-in’ option.
    I can populate the ‘fill-in’ text with what I want, but I can’t figure out how to have its associated radio button selected, rather than the radio button beside the product dropdown (see below for an example of what I’m using at the moment)

    Is what I’m trying to do possible, or will I have to change over to another question type?

    Thanks,
    Andrew

    Example (populates ‘Specify your own value’ field, but doesn’t select it) :
    …/NewForm.aspx?Case ID :=411810276&Product Name : : Specify your own value:=Windows XP

    Non-working example of what I’ve tried:
    ../NewForm.aspx?Case ID :=411810276&Product Name : : Choose Option=Product Name : : Specify your own value:&Product Name : : Specify your own value:=Endpoint Protection

  7. Brian says:

    Thank you for sharing this approach/code for prepopulating SharePoint Form Fields. I was able to get this up and running very quickly but do have a question please.

    What if I wanted to configure the JQuery so that I would not have to pass the information needed via a string? Is it easy to do with the above code and do you have an example of how I would go about doing so?

    Here is my use case/reson for asking. I would like to prepopulate a memo field with an number of items which in turn makes the URL very long and unusable (in some cases).

    Thoughts?

    • I would like to do something similar.

      I have a Content Editor Web Part that has code to suppress fields without having to pass all the fields to suppress via a URL Query String.

      Next I would like to be able to specify default values for some fields in a Content Editor Web Part.

      Looking at the code it seems like a case of replacing the Query String decomposition and replacing with a series of calls such as:

      prepop(”Title”, “Defaulted Title string”);

      Am I on the right track? I am not a javascript expert so I am at a loss as to how to modify your code to call from within the CEWP.

      Finally to bring all this together I would like to be able to use the Query String in a CEWP
      and wrap the field suppression code and the default value code inside an if or case/switch statement. This would allow one passed paramter to configure a series of fields in the form.

      The net result being

      .newform.aspx?IssueType=Escalation

      CEWP pseudo code then contains:

      /// Hide Fields

      _spBodyOnLoadFunctionNames.push(”hideFields”);

      function findacontrol(FieldName) {

      var arr = document.getElementsByTagName(”!”);
      // get all comments
      for (var i=0;i 0)
      { return arr[i]; }
      }
      }

      function hideFields() {

      /// use this format to suppress specific fields.

      /// var control = findacontrol(”TrackingID”);
      /// control.parentNode.parentNode.style.display=”none”;

      /// End of field suppression section
      }
      /// Here comes the customization section

      If QueryStringParam=”Escalation”

      /// Suppress these fields
      var control = findacontrol(”TrackingID”);
      control.parentNode.parentNode.style.display=”none”;
      var control = findacontrol(”Status”);
      control.parentNode.parentNode.style.display=”none”;

      /// Set these default values

      prepop(”Status”,”1-New”);

      EndIf

      If QueryStringParam=”Issue”

      /// Suppress these fields
      var control = findacontrol(”TrackingID”);
      control.parentNode.parentNode.style.display=”none”;
      var control = findacontrol(”Priority”);
      control.parentNode.parentNode.style.display=”none”;
      var control = findacontrol(”Severity”);
      control.parentNode.parentNode.style.display=”none”;

      /// Set these default values

      prepop(”Status”,”1-New”);
      prepop(”Description”,”A short and sweet description);

      EndIf

  8. jj_in_atlanta says:

    I can’t get this to work with a multi-select using MOSS 2007 – when I trace through the code it isn’t able to determine what type of control it is. I can see that it gets to the section starting at line 50 of your listing above… but s1.length is always zero –
    any suggestions? i’ve been looking at it but can’t figure out the issue.

    Thanks

    • jj_in_atlanta says:

      I mis-spoke above – I was actually having a problem getting the code to populate a checkbox list.
      I was able to modify the code to detect that and populate it by adding the code below. It appears to work OK in IE and FireFox – no promises.

      ckBoxes=$(elm).find(”span.ms-RadioText”)
      if (ckBoxes.length>0){job=100}; //Checkbox List
      . . .
      case 100: //Checkbox List
      $.each(vals,function(i,e){
      var V=alltrim(e); // the individual value
      $.each($(ckBoxes).find(”label”),function(i,e){
      if ($(e).text()==V) { $(e).prev().attr(’checked’,true);}
      });
      });
      break;

  9. dave says:

    I have this working perfectly apart from where there is a single quote ‘ in the query string…for example &surname=O’Neil

    The query string simply stops after the ‘ character.

    The same happens with &…for example Title=John & Jane Books

    Any ideas?

  10. Darko says:

    Not sure why it does not work for me. I am trying to populate srid field with a number. Here is my URL:

    http://website/subsite/Lists/Feedback/Item/newifs.aspx?srid=10

    I edited the newifs.aspx page, added CEWP to the page, uploaded my script.txt with your script above to sharepoint, linked to it in CEWP web part, and then tryed the url above which for some reason does not pre-populate my srid field.

    Any ideas? Am i missing something?

  11. sander says:

    Hi,
    Very Cool Thank you very much. Usin’ the solution in 3 forms already.
    BUT(!!!!)
    I cannot get it to work with a LookUp?! One value of the lookup is “LookUp 1″
    Any ideas?
    I tried all these
    ../Demo/Lists/Child/NewForm.aspx?Editie=@1
    ../Demo/Lists/Child/NewForm.aspx?Editie=LookUp1
    ../Demo/Lists/Child/NewForm.aspx?Editie=LookUp%201
    ../Demo/Lists/Child/NewForm.aspx?Editie=LookUp 1

    THNX!

    • Brendan says:

      Hey,
      This is probably because you are using the newer library for JQuery; I found that anything after like 1.3.2 didn’t let lookup’s work…try to make sure that it references 1.3.1 or 1.3.2 and not 1.4 anything and see if that makes a difference.

      • Sander says:

        Thnx that did the trick!
        Turns out that you can pre-fill the TITLE column OOB! Thus without the need of this script?!
        Tested this on a customer site :-)

Trackbacks

Check out what others are saying about this post...
  1. [...] may have seen the previous version of this script. At any rate, my goal was to create a script that required very little configuration and allowed [...]




Notify me of comments to this article:


Speak and you will be heard.

We check comments hourly.
If you want a pic to show with your comment, go get a gravatar!