1,372 articles and 9,189 comments as of Tuesday, February 9th, 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

53 Responses to “JQuery for Everyone: Pre-populate Form Fields”
  1. AutoSponge says:

    @Mike O,

    The problem comes from IE (only) switching between SELECT and INPUT tags after the 20-item mark. You should probably move to the more tested code at spff.codeplex.com and see if you still have problems.

  2. 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.

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!