Wednesday, March 3, 2010

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

view source

print?

001

<script
type="text/javascript">

002

//?PageView=Shared&ToolPaneView=2


 

003

if(typeof jQuery=="undefined"){

004

    var jQPath="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/";


 

005

    document.write("<script
src='",jQPath,"jquery.min.js'
type='text/javascript'><\/script>");

006

}


 

007

</script>

008

<script
type="text/javascript">


 

009

/*

010

 * Prepopulate form fields in SharePoint


 

011

 * Copyright (c) 2008 Paul Grenier (endusersharepoint.com)

012

 * Licensed under the MIT (MIT-LICENSE.txt)


 

013

 */

014

(function(){


 

015

    var params = window.location.search.substring(1).split("&"),

016

        kv = {},


 

017

        opts,

018

        sp=/%20|\+/g,


 

019

        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,

020

        date=/([1-9]|0[1-9]|1[012])[\-\/.]([1-9]|0[1-9]|[12][0-9]|3[01])[\-\/.](19|20)\d\d/,


 

021

        clean = function(str){

022

            return str.replace(sp," ");


 

023

        },

024

        getKv = function(){


 

025

            $.each(params,function(i,e){

026

                var p=e.split("=");


 

027

                kv[p[0]]=decodeURIComponent(p[1]);

028

            });


 

029

            return kv;

030

        };


 

031

    jQuery.prepop = function(){

032

        $.each(getKv(),function(k,v){


 

033

            k=clean(k);

034

            v=clean(v);


 

035

            var f=$("[title='"+k+"']"),

036

                job;


 

037

            if (f.length>0){

038

                if (f[0].type=="text"){job=10;} //text


 

039

                if (f[0].type=="checkbox"){job=20;} //checkbox

040

                if (f[0].tagName=="SPAN"&&f.hasClass("ms-RadioText")){job=30;} //radio


 

041

                if (f[0].type=="select-one"&&f[0].tagName=="SELECT"){job=10;} //choice and non-IE lookup

042

                if (f[0].tagName=="TEXTAREA"){job=10;} //textarea


 

043

                if (f[0].type=="text"&&f[0].opt=="_Select"){job=70;} //IE lookup

044

                if (v.match(date)){job=40;} //date


 

045

                if (v.match(datetime)){job=50;} //datetime

046

            }


 

047

            if (f.length===0){

048

                var elm = $("nobr:contains('"+k+"')");


 

049

                if (elm.length>0){

050

                    elm = elm.parents("td").next()[0];


 

051

                    var s1 = $(elm).find("select:first"),

052

                        s2 = $(elm).find("select:last"),


 

053

                        p1 = $(elm).find("textarea[title='People Picker']"),

054

                        p2 = $(elm).find("div[title='People Picker']"),


 

055

                        vals = v.split(",");

056

                    if (s1.length>0){job=80;} //multi-select


 

057

                    if (p1.length>0){job=90;} //people picker

058

                }


 

059

            }

060

            switch (job){


 

061

            case 10:

062

                if (v.substring(0,1)=="@"){


 

063

                    opts = f[0].options;

064

                    $.each(opts,function(i,e){


 

065

                        if (opts[i].value==v.substring(1)){f[0].selectedIndex=i;}

066

                    });


 

067

                }else{

068

                    f.val(v);


 

069

                }

070

                break;


 

071

            case 20:

072

                if (v.toUpperCase()=="TRUE"||v=="1"){f[0].checked=true;}


 

073

                if (v.toUpperCase()=="FALSE"||v=="0"){f[0].checked=false;}

074

                break;


 

075

            case 30:

076

                if (v.toUpperCase()=="TRUE"||v=="1"){f.find("input:radio").click();}


 

077

                break;

078

            case 40:


 

079

                v=v.replace(/[\-\/.]/g,"/");

080

                f.val(v);


 

081

                break;

082

            case 50:


 

083

                var dt=v.split(" "),

084

                    d=dt[0].replace(/[\-\/.]/g,"/"),


 

085

                    t=dt[1],

086

                    hm=t.split(":"),


 

087

                    hh=hm[0].replace(/^0/,""),

088

                    mm=hm[1],


 

089

                    ap=dt[2].toUpperCase();

090

                f.val(d);


 

091

                f.parent("td").siblings("td.ms-dttimeinput")

092

                    .find("select:first").val(hh+" "+ap)


 

093

                    .parent("td").find("select:last").val(mm);

094

                break;


 

095

            case 70:

096

                if (v.substring(0,1)=="@"){


 

097

                    ShowDropdown(f[0].id);

098

                    opts = $("#_Select")[0].options;


 

099

                    $.each(opts,function(i,e){

100

                        if (opts[i].value==v.substring(1)){$("#_Select")[0].selectedIndex=i;}


 

101

                    });

102

                    f.blur();


 

103

                }else{

104

                    f.val(v);


 

105

                    ShowDropdown(f[0].id);

106

                    f.blur();


 

107

                }

108

                break;


 

109

            case 80:

110

                opts = s1[0].options;


 

111

                $.each(vals,function(i,e){

112

                    var V=e;


 

113

                    $.each(opts,function(i,e){

114

                        if (opts[i].text==V){


 

115

                            s2.append("<option
value='"+opts[i].value+"'>"+V+"</option>");

116

                        }


 

117

                        if (V.substring(0,1)=="@"){

118

                            if (opts[i].value==V.substring(1)){


 

119

                                s2.append("<option
value='"+V+"'>"+opts[i].text+"</option>");

120

                            }


 

121

                        }

122

                    });


 

123

                });

124

                break;


 

125

            case 90:

126

                var p=vals.join(";");


 

127

                p1.val(p);

128

                p2.html(p);


 

129

                break;

130

            //default:


 

131

            }

132

        });


 

133

    };

134

})();


 

135

$(function(){

136

    $.prepop();


 

137

});

138

</script>

0 comments: