Geeks With Blogs

News





The SharePoint Hillbilly Fewer Big Words... More Pretty Pictures...

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 stuff.  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 .  A table element would be .

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:

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”:

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:

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:

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”:

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:

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
Posted on Saturday, August 20, 2011 4:09 PM | Back to top


Comments on this post: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
<borat_tone>Very nice</borat_tone>
Left by Stacy Draper on Aug 20, 2011 4:23 PM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
The api has changed in 1.6 for a number of elements. The jQuery team is suggesting to use .prop() to set check box properties.

http://api.jquery.com/prop/

Here's a good write up about the changes to the api regarding .attr() and .prop().

http://www.timmywillison.com/2011/A-New-jQuery.attr-and-the-New-jQuery.prop-Method.html

Cheers,
Matt
Left by Matthew Bramer on Aug 20, 2011 4:30 PM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
@Matt: I think your reference is outdated, as some changes have been rolled back in jQuery 1.6.x.
Left by Christophe on Aug 20, 2011 5:50 PM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
I think it's still valid. The blog article may be old, but jQuery.com keeps very close tabs on their API pages. I found this from the first link I posted:

if ( elem.checked )
if ( $(elem).prop("checked") )
if ( $(elem).is(":checked") )

If using jQuery 1.6, the code if ( $(elem).attr("checked") ) will retrieve the actual content attribute, which does not change as the checkbox is checked and unchecked. It is meant only to store the default or initial value of the checked property. To maintain backwards compatability, the .attr() method in jQuery 1.6.1+ will retrieve and update the property for you so no code for boolean attributes is required to be changed to .prop(). Nevertheless, the preferred way to retrieve a checked value is with one of the options listed above. To see how this works in the latest jQuery, check/uncheck the checkbox in the example below.


They are suggesting you to use .prop(). You can use one or the other, but jQuery isn't that great with backwards compatibility. I'd use the method they suggest.

Cheers,
Matt
Left by Matthew Bramer on Aug 20, 2011 8:04 PM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
SPServices is nice but I think Marc covers that extensively on his own site. More information about manipulating the DOM in various situations with pure JavaScript/jQuery will be useful. Information about the Client Object Model as it relates would be good too. Too much reliance on 3rd party libraries is a hurdle for acceptance (and you're already one level deep requiring jQuery).
Left by Bil Simser on Aug 22, 2011 10:16 AM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
@Matt: I maintain that the article is outdated (for example saying that attr... doesn't work anymore).

@Mark: one question, did you test all those techniques across browsers? btw it's really convenient to have them all in one article, thanks!
Left by Christophe on Aug 27, 2011 8:45 PM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
Hey Christophe,

I did NOT test all the above code in multiple browsers when writing this article. I was testing in IE8. I HAVE however used the above principles in IE7, Firefox, and Chrome.

As far as I know, the above should work fine in multiple browsers and the only thing that is really different is the +/- 20 items in a lookup in IE. However, SHOULD and DOES seem to be very important distinctions in SharePoint. :)
Left by Mark Rackley on Aug 28, 2011 9:25 AM

# re: A Dummies Guide to SharePoint and jQuery–Getting & Setting SharePoint Form Fields
Requesting Gravatar...
Does anyone happen to know how to add a line break to the Display Name property so that it shortens the width of the column?
Left by Harry on Aug 31, 2011 3:27 PM

Your comment:
 (will show your gravatar)


Copyright © Mark Rackley | Powered by: GeeksWithBlogs.net