A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields

Originally posted on: http://geekswithblogs.net/SoYouKnow/archive/2011/08/20/a-dummies-guide-to-sharepoint-and-jqueryndashgetting-amp-setting-sharepoint.aspx

Part 2 of a Dummies Guide blog posts deals with setting SharePoint’s form fields using jQuery. If you haven’t read part 1 and are a dummy like me, then go do that first because I’m going to assume you’ve read it and not go back over those pieces:

A Dummies Guide to SharePoint and jQuery–Getting Started

 

So, I have touched on this topic before in a couple of other blogs, but wanted to make it part of this series so that it was more related. One of the most common things you’ll do with jQuery in SharePoint is use it to set default values for form fields or get the current value of a SharePoint form field. This comes in handy for doing things like cascading drop down lists or  setting fields to a default value that needs to be calculated. You can even do things like look at who the current user is and fill in values specific for that user. The possibilities are really pretty endless and only limited by your ability to write JavaScript and interact with data as you need to.

Elements & Attributes

So, before you can effectively set form values in SharePoint using jQuery it is critical you understand the concept of elements and attributes of an element. An element is defined as a tag name of a DOM node. Ugh… now I have to tell you what the DOM is…  and a node? dang…  rat’s nest anyone?  Okay… let’s try this again….

DOM – Document Object Model

The Document Object Model or DOM is basically the HTML source of your page. I find that w3schools.com is a great reference site for basic information, so you can see how they describe the DOM here.  jQuery searches this DOM to find and manipulate the information that it needs. When using jQuery, the DOM is always changing so if you are using your browser to “view source” you are only seeing the state of the DOM after the page is first loaded before it is manipulated by JavaScript, it does not show the current DOM if any changes have been made. You will utilize one of the multiple JavaScript developer/debugger tools to view the DOM which we’ll hopefully get into in another blog post.   Okay.. fine… if you are using IE Developer Tools (launched by pressing F12) you can view the current state of the DOM by “View->Source->DOM(Page)”

image

Okay… so do you understand what the DOM is??? 

Nodes & Elements

So… back to w3chools.com to explain a DOM Node:

According to the DOM, everything in an HTML document is a node.

The DOM says:

  • The entire document is a document node
  • Every HTML element is an element node
  • The text in the HTML elements are text nodes
  • Every HTML attribute is an attribute node
  • Comments are comment nodes

If you still have questions about what a node is, read about DOM nodes from the w3schools site using the link above, no reason for me to reinvent the wheel.

So… a NODE is <node_name>stuff</node_name>.  Got it?? So, what is an element? Without getting too complicated, an element IS a node within the DOM. So, when I refer to an “input” element… you would search in the DOM for <input …>.  A table element would be <table…>.

Clear as mud? I’m trying to not get too bogged down in the details here because I want to finish this post before next year. So, if you think I’m not going into enough detail on a subject, please feel free to blog about it and I’ll be happy to link to your blog from here.  Smile

So, we know that our page source is the DOM, and the DOM has element nodes? Right?

ID’s & Attributes

One of the main reasons I use jQuery is that it comes with a lot of functionality to help you search the DOM and it’s elements allowing you to modify these as you need to. The question becomes, how do you FIND the specific element you are looking for??? Right? Before we can set the value of a form field in jQuery (which was the reason for this post if you remember) we have to find it? So.. how do we do this?? Well, the most straight forward way is to use the ID of an element, let’s look at the input field below:

<input type=”text” id=”myText”>

So, there are 3 ways I can think of off the top of my head to search for that element (ugh… I know.. would be nicer if there was only one).  The easiest and most straightforward way is to use the element’s “id” value like thiis:

$(“#myText”)

So, the above line would return my element. ID’s are awesome for this, but your id’s must be unique!! So, how could we use this to get or set a value of a SharePoint form field?  Well.. let’s look at the source code for a field with the display name “My Text Field”:

<input name=”ctl00$m$g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb$ctl00$ctl04$ctl00$ctl00$ctl00$ctl04$ctl00$ctl00$TextField” type=”text” maxlength=”255″ id=”ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField” title=”My Text Field” class=”ms-long” />

Wow.. SharePoint really? You generate your id’s like that?  So, using the method I just told you to use, you would have to use the following jQuery to get this element:

$(“#ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl00_ctl00_ctl00_ctl04_ctl00_ctl00_TextField”)

Well.. this would work in a pinch, but that id is not consistent and you have no way of knowing what it would be without viewing the page’s source.  There would be no way to create reusable code using that id… so, what do we do?

Let’s look closer at the element for our field… is there any helpful information? There is a section of the element that is ‘title=”My Text Field”. Maybe we can use this?  But what are we looking at? What is “title”?  “title” is an ATTRIBUTE of the element, and the value of that attribute is our SharePoint field’s display name.  With jQuery we have the ability to search for an element with a specific attribute! Rock on jQuery… so that would look like:

$(“input[title=’My Text Field’]”)

So, the above jQuery says “Search all the input elements for one with the attribute of title with a value of “My Text Field”. Viola… we now have a reusable way of finding form fields in SharePoint.

Attributes are awesome, and as you start writing more and more jQuery you can use attributes to store all sorts of cool information.  I like to use them to store item ID’s so I can easily know which list item should be read/updated/or deleted based upon my user’s action. You can even use them to store the ID’s of related list items that you want to do something with. Again, possibilities are only limited to you ability to write jQuery. 

Getting & Setting SharePoint Form Fields

Okay, now that you have the form field’s element, how do you get or set the value of the form field?  This turns out to be an easy exercise. To get the value of the element we would use:

var textValue = $(“input[title=’My Text Field’]”).val();

To set the value we would use:

$(“input[title=’My Text Field’]”).val(textValue);

So, that’s all fine and dandy for setting regular text fields. right? All you have to do is remember to replace “My Text Field” with the display name of your text field for your SharePoint list item.  But what about the other SharePoint fields? They aren’t all going to be this easy?  Well.. yes and no. Some are that easy, and some are a pain in the butt.  Let’s take a look at a few of these.  If you don’t see your exact question answered a good place to always start is to look at your DOM and see how SharePoint is generating the element (that’s how I got started).

Lookup and Choice fields

Lookup and Choices fields are rendered as a select element:

<select name=”ctl00$m$g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb$ctl00$ctl04$ctl02$ctl00$ctl00$ctl04$ctl00$DropDownChoice” id=”ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl02_ctl00_ctl00_ctl04_ctl00_DropDownChoice” title=”My Choice” class=”ms-RadioText”>

So, the above Choice field has a display name of “My Choice” an it is of type “select”.  Our jQuery for getting and setting this field are:

var mySelectValue = $(“select[title=’My Choice’]”).val();

$(“select[title=’My Choice’]”).val(mySelectValue);

It is important to note that you are setting and getting the option Value, not the displayed text. Also, if you go above 20 items things get really funky if you are using IE.  Luckily I already did a whole blog post on that:

Setting SharePoint Lookup Lists w/ jQuery (+/- 20 items)

Date Fields

Date fields act just like regular text fields, you just need to be sure to set the text to a valid value if you are setting the field:

<input name=”ctl00$m$g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb$ctl00$ctl04$ctl03$ctl00$ctl00$ctl04$ctl00$ctl00$DateTimeField$DateTimeFieldDate” type=”text” maxlength=”45″ id=”ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl03_ctl00_ctl00_ctl04_ctl00_ctl00_DateTimeField_DateTimeFieldDate” title=”My Date Field” class=”ms-input” AutoPostBack=”0″ />

So, getting and setting that value would be:

var myDateValue = $(“input [title=’My Date Field’]”).val();

$(“input [title=’My Date Field’]”).val(myDateValue);

Checkboxes

Okay, let’s look at a checkbox fields source for a checkbox field with the display name “My Check  box”:

<input id=”ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField” type=”checkbox” name=”ctl00$m$g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb$ctl00$ctl04$ctl01$ctl00$ctl00$ctl04$ctl00$ctl00$BooleanField” checked=”checked” />

Oh crap… where’s our title attribute? How are we going to set or get this field value? Ugh.. my project is due in 10 minutes and you are telling me I can’t use this method with a Checkbox field? WTF?  Dude.. you suck…

First of all.. you have some anger issues… seek help… second of all, let’s dig a little deeper. Let’s look at the ACTIVE DOM… the source above is the DOM from just doing a “view source”.  If we view the active DOM our field looks like:

<INPUT id=”ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField” title=”My Check  box” CHECKED type=”checkbox” name=”ctl00$m$g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb$ctl00$ctl04$ctl01$ctl00$ctl00$ctl04$ctl00$ctl00$BooleanField” value=”on” />

And look, there’s our title attribute.  So, what happened here?  Let’s go back to the original page source and do a quick search for our element id, and look what we find:

document.getElementById(‘ctl00_m_g_1e7ef826_b2be_47b2_8c81_60e75c9af0bb_ctl00_ctl04_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_BooleanField’).title=’My Check  box’;

So, part of generating the page is setting this title attribute manually. Interesting the things you can find out by viewing the page source and dissecting it.  Why was this done? I’m sure there was a good reason.  I just don’t know it.  Okay..enough rambling… sorry… to check if a check box is checked:

if( $("input[title='My Check  box']").is(':checked')) 
{ 
   alert("it's checked"); 
} 

If you want to check or uncheck a checkbox programmatically you simply need to set or remove the “checked” attribute of the element. To uncheck a checkbox:

$("input[title='My Check  box']").removeAttr('checked');

To check a checkbox:

$("input[title='My Check  box']").attr('checked','checked'); 

 

People / Group Fields

Okay… these special fields necessitate a blog post all their own. It’s far too much to get into in the one.  If you really can’t wait until I get around to writing the blog post don’t be scared to view the DOM and wrap your head around these bad boys.

That’s it?

Well, yes.. you were expecting more? The only other thing I can think of to add off the top of my head is that if you are using SharePoint 2007 you may have noticed you do not have the “Edit Page” option for default form pages.  Well.. you can get around this by manually putting these pages into Edit Mode.  You do this by appending “&ToolPaneView=2” to the end of the pages URL.  After you do that you can add all the web parts you want to get your jQuery in the page without having to open it up in SPD.

So, what’s next for this series? I’d love to hear what YOU want? Maybe I’ll do a simple intro for SPServices or the Client Object Model? Regardless, it will hopefully be something you find useful.

As always, I hope you found something helpful, feel free to add to the conversation below and thanks again for stopping by.

Up Next:
A Dummies’ Guide to SharePoint and jQuery–A Real World Example

Families in Germany who are facing divers health problem, such persons can buy drugs from the Web without prescription. With the market flooded with divers web-sites selling sundry medicaments, purchasing medicines from th WEB is no longer a trouble for common man. Certain medications are used to treat infections caused by dental abscesses. Of course it isn’t all. If you’re concerned about erectile soundness problem, you probably know about Xenical and Hoodia. Probably every adult knows about Garcinia. (Read more PhentermineXenical). The symptoms of sexual soundness problems in men turn on impossibility to have an erection sufficient for sexual functioning. Certain medications may add to sex drive difficulties, so its substantial to cooperate with your soundness care professional so that the prescription can be tailored to your needs. Preparatory to capture Levitra or other medicament, speak to your dispenser if you have any allergies. Talk to your heartiness care producer for more details. Preparatory to ordering this remedy, tell your doctor if you are allergic to anything.

1 Comment

  1. Mark: Thanks for your great class today at TechCon. I’m going to work through these awesome how-to’s. Wanted to let you know that your inline links to related posts are still pointing to SharePointHillbilly.

Comments are closed.