Add functions and events to SharePoint form fields
Do you sometimes wish to make some special form validation or other javascript actions on SharePoint form fields (like for example onchange, onfocus, onblur, etc?). You can add special functions on events to the SharePoint form fields using JavaScript. All you need to do is
1. Write your JavaScript function
2. Use the getField function I was writing about to refference the SharePoint Fiedl
3. write the following code:
getField('[field_type]','[field_title]').[event] = function() {[function_name]};
Let me demonstrate in an example below. I have a SharePoint List with a field "Menu" that is a lookup field to Title list "Menu". I’ve created another field "Menu_id" that is a lookup to the same list, but instead of Title it should select the ID. These two fields need to select the same item from the list Menu.

Now we’ll prepare a one-way synchronization. We’ll want those two fields synchronized when selecting the item from the "Menu" dropdown. So we’ll add an "onchange" event to the "Menu" select field.
1. Add a Content Editor Web part to the page using this method
2. Edit the Source of the content editor web part add the script code, insert the getField function, write your function and use function above. The full code is below
<script type="text/javascript">
function getField(fieldType,fieldTitle) {
var docTags = document.getElementsByTagName(fieldType);
for (var i=0; i < docTags.length; i++) {
if (docTags[i].title == fieldTitle) {
return docTags[i]
}
}
}
function syncDropDowns() {
selectedId = getField('select','Menu').options[getField('select','Menu').selectedIndex].value;
for (i=0; i<getField('select','Menu_id').options.length; i++) {
if(getField('select','Menu_id').options[i].value == selectedId) getField('select','Menu_id').options[i].selected='selected';
}
}
getField('select','Menu').onchange = function() {syncDropDowns()};
</script>
This is an example made with CEWP and in the SharePoint. The same works also in the Data View Webpart.




Great stuff, I was looking for a solution to this very same problem and had just gone down the custom field control route. I’m going to back out my half working code and do it this way istead. Sooo much simpler. Nice solution.
Thank you very much for the article.
I wanted to do some simple javascript functions based on the “onFocus” method of a textfield.
However, the
getField(‘input’,'DriverName’).onchange = function() {WriteValues()};
I have inplace does not seem to bind the “onFocus” event to the field. Do I need to set up a “listener” to check the field every 10 milli-seconds or so?
It just seems that the onFocus call needs to be directly attached to the field.
Any thoughts on this would be appreciated.
Cliff
If you need to add onFocus event, then change from
getField(‘input’,'DriverName’).onchange = function() {WriteValues()};
tp
getField(‘input’,'DriverName’).onfocus = function() {WriteValues()};
However, the onFocus will only trigger when you select the field. If you want keystroke interactivity, I suggest using the onkeyup event rather.
Really cascading dropdown post was good, I had followed the step you mentioned, but where to add the “onchange” event when I open the newform.aspx page in sharepoint designer I cannot add “onchange” change, Can you please tell me how to add the “onchange” event where and how?
Thanks
Vijai Kumar G
Hi ,
Nice post .
I have a problem .
We want to change the FormFilds for the lookup list mutivalue .
Now there are two list box and you can move one element from one box to another box . Now we need to remove the left box and use a tree view
can someone help me ?
Regards Luca
I can’t get the code to fire. I know what my fieldTitle is but maybe it’s because I don’t know the fieldType? How do I determine which field type to plug into the code? I’ve seen you use ‘select’ and ‘input’ used… Thank you!
@ karen:
Which type of field do you want to manipulate? Maybe the Internet Explorer Developer Toolbar can help you to reference the field.
@luca:
Can you explain a bit more. Do you perhaps have some link or screenshot?
@gvijaikumar:
Sorry for not replying for long. You don’t even need SharePoint designer in the newform.aspx page. You can add the parameters &PageView=Shared&ToolPaneView=2 to the URL of the newform. Then you can add the content editor webpart, edit it’s source and then make the code in there.
When I try to set the order in the data view it always reverts back to the original Data source information.
Any ideas why this would happen?
I did all that was said above.
But when I select a particular item in one drop down list, the other is not getting updated. What could be the issue. Could you please help me out.
Hi Anna.
Reasons can be different. If there is one error in javascript the whole script stops working.
How I usually debug such scripts is to put alerts in different phases of javascript to see untill where the functions is working correctly.
Hi, Ishay!
The problem could be if the dropdown is a lookup field to a list that has more than 20 elements. In that case the "Select" element becomes an "Input". The best way is to make an if.
Hi, I would like to say thanks for your article and I was able to manipulate the lookup field values. Basically I just wanted to display another field if a particular value was chosen in the lookup field and was banging my head how to do it…
brilliant work!
Hi , thank you but in my list there is just 10 elements , its look like the line : " var docTags = document.getElementsByTagName(fieldType); " get only 1 element ( the SHAREPOINT search scops button ) and ignore the other , i open the "view source" and verified the other select tags .
This works great for lists under 20 items, is there a way to use it for lists that have more than 20 items?
Do you have any idea how to implement this in IE7? In Fireforx the SPFieldLookup is a but in IE7 it is that then calls a HandleChange() function onChange. Any help would be appreciated.
hi
i try to add a functions to my newForm.aspx
and iv'e a problem , the 'getfield' function does not recognize the control ( the element )
i try this for drodownlist with header 'menu' :
getField('select','menu').onchange = function() {syncDropDowns()};
where im go wrong ?
Thanks for a very useful article. I am trying to achieve something similar. I have a list with fields Email and Status. What I want to do is everytime the Status is updated to 100% for an item, I want to send a thankyou email to the address I have for that listitem in the field Email. Once the status is updated to 100% for a listitem, it will always have the same value. I just want to send an email once, the time it is first updated to 100%. Can you give me some idea on how can I achieve this?
This can't be achieved through just client-side, since this would pose too open hole for any spamming. Ho I'd recomend doing it is by creating a hidden field and program an event receiver that would check when the status is at 100%. then it would send an email and update the hidden “Mail Sent” field to yes to avoid further resends.
Hope I didn't complicate too much.
HI
this can't be work on fields on new form?
Where did all the previous comments go?
I'm trying to keep the sync working even though there might be 20 items or more. Even though the Lookup field changes to input is there still an .onchange event available? Have you had any luck with this.
Thanks
@Marcus and couple of other visitors: Yes, the problem arises with more than 20 items in lookup. If that is the case, SharePoint Designer team blog has a great article on exactly this topic:
http://blogs.msdn.com/sharepointdesigner/archive/2007/06/13/using-javascript-to-manipulate-a-list-form-field.aspx
I have been using that article quite a bit lately and it has proven to be very useful. It appears that the onchange event is taken by a “HandlChange()” function and overriding it is not possible. I am trying to bind to the onmouseup event which based on article: http://autosponge.spaces.live.com/blog/cns!D7F85948C20F0293!397. is possible but testing so far has proven unsuccessful.
unable to fire the function on onchange()
Please help
On which type of field are you using the onchange event? Is it a dropdown field or an input field? If using on input field I’d rather use the onkeyup event, which means the event after the key was pressed.
Also please note that you need to put onchange without brackets.
Has anyone been able to make this code work with Lookup items greater than 20 yet. Need a code sample to work from, not very good with Javascript and I can’t figure it out.
Thanks,
-MO
Boris,
If I use the onkeyup event, instead of onchange–do I only need to alter the script by specifying “input” fields, instead of “select” fields–for Lookup’s to a column that has more than 20 items?
@Mike: Unfortunately when you have the lookup field to a list with more than 20 items the whole story becomes much more compliceted:
The way that the lookup field renders in IE is an input field and a hidden (autogenerated) select field. Both of those are connected with “onchange” and “onkeyup” event and this makes the whole story more complicated. Please see the link that I’ve already posted in comments above on how to work with lookups with more than 20 items.
Boris,
If you could just guid me how to “adapt” the code for more than 20 items–I would be extremely grateful. I just can’t figure it out–my javascript is not that strong…
Thx,
-MO
Hi Boris,
First thanks for this excellent article. Even though I am not a programmer, I manage to get it to work, even with 2 different cascading field in the same form.
Unfortunately, just as Mike, I am in front of the “more than 20 items” problem, and I just can’t figure it out with the little knowledge in javascript I have. Would it be possible for you to give a little example to adapt the script from the link you gave ?
thanks
Hi Boris,
Great article. i did manage to raise onblur event of the sharepoint textfield (say Title). But the problem is blur event is firing only when form is fresh. Fresh means when i am browsing this form in add mode and every fields of the forms is empty. I write something in the SP textfield and as i leave the textbox it fires a blur event which is fine.
But when i submit the form where other validators viz. requirefield validator are also placed and validated. I means there is a field location which is set to be validated by required field validator. and let’s say i leave location field empty. its validator raised.
So, After this blur event of the SP TextField title is not firing. Also would like to mention that AJAX is enabled on this Page.
could please ponder on this problem?
Thanks & Regards
Khushi
[...] Gomiunik on 26-10-2009 Due to a lot of comments and questions to my last year’s post about Attaching functions to SharePoint form fields concerning especially lookup fields on which the demo was made, I’ve decided to take a deeper [...]
Hey, everyone who’s having troubles with lookup fields (especially the ones with more than 20 items). I’ve written a new post explaining Lookup field in a bit more details:
http://www.sharepointboris.net/2009/10/sharepoint-lookup-field-how-does-it-work-and-how-to-add-javascript-event-handler-function-to-it/
@Khushi: Thanks for the feedback. Not 100% sure I understand the problem. Perhaps you can try the “onkeyup” event for the textfield. Otherwise the blur event is meant always when the field looses focus. If you submit the form without bluring the field the event doesn’t happen. There is another way to “attach” your own custom javascript to just before the form is submitted, but that is an article I’m preparing.
For some reason, this isn’t working for me. I’ve tried adding in some alerts to see what’s happening and those aren’t even triggered.
#
# function getField(fieldType,fieldTitle) {
# var docTags = document.getElementsByTagName(fieldType);
# for (var i=0; i < docTags.length; i++) {
# if (docTags[i].title == fieldTitle) {
# return docTags[i]
# }
# }
# }
#function setVisibility() {
#alert('here2');
#}
#getField('select','Enhancement').onchange = function() {alert('here')};
#getField('select','Enhancement').onchange = function() {setVisibility()};
#
The code generated by Sharepoint is
#
#
#Yes
#No
#
What am I missing?
Thanks!
@Brett: Hi. Can you try the following:
1. The code must be inserted after the form (so the elements already exist)
2. If the code still doesn’t work, it can probably be that the code runs before the fields are rendered by your browser. What you can try is to enclose the lines that attacth event in a function like this:
function attachEvents() {
getField(‘select’,'Enhancement’).onchange = function() {alert(‘here’)};
getField(‘select’,'Enhancement’).onchange = function() {setVisibility()};
}
and then at the end of script put this function in a _spBodyOnLoadFunctionNames array so it will execute when SharePoint DOM is ready:
_spBodyOnLoadFunctionNames.push(“attachEvents”)
Hope this will help.
Hi Boris Gomiunik ,
I have read the post and it was useful to me. but can you can help with this problem.
I am having a radiobutton field with two options yes and no
1. how can we make it appear in horizontal instead of default vertical postion.
2. how can we write javascript function to show the entire row below it depending upon radiobutton field value user selected
i have tried OnClientClick but i couldn’t find that
is there any way to do this using SPD 2007
thanks
@Sreedhar:
).
1. to make the radiobuttons appear in horisontal position you’d need to remake the DOM of the radio buttons. Usually radio buttons choice field is rendered as a table and each row is containing one choice. So you’d need to loop through rows 2 to n (n being total number of rows) and moving the innerHTML to additional tablecells created in the first row. It would require a bit of coding, for sure.
2. You can refference the row below and hide it as soon as the document is loaded. Then depending on choice you’d show/hide this. Can you try the onclick event instead of onclientclick (the later is ASP.NET
Please stay tuned on my series on HTML DOM manipulation with JavaScript.
I don’t know if anyone will respond to this anymore, but I’ll try.
I don’t understand this example. Where is this title list “menu” located? What column from it are you targeting? Since the code example isn’t commented at all, I can’t determine when “menu” means the menu field and when it means the list.
The rest is explained out of the code. There is another list that is the source of the two dropdowns in the screenshot, but that doesn’t play a major role here.
Hi,
Thanks to you, i have copied your javascript and then put my content editor web part.
But i don’t know, how to call the javascript function in my edit dataform webpart dropdown list. can you say how to call this function ? (aasai04@gmail.com)
The following code for my dropdown:-
I hope my writing abilities get on be competitive with yours, your articles was
so well written and thought away also shows this became clearly researched.
How do I add a hidden field? I don't have sharepoint designer and I am working with windows portal server 2003. I have used content editor for adding some menuitems using javascript but that is pretty much it. Could you please do an article or something on this…this would sure be a very useful topic….ofcourse if you have some time for this….I will also keep trying from my side, if any success, will definitely share.
What is your question….it was not clear to me. you can't just open the newform.aspx page in visual studio and add events from there, can you? I haven't been able to do so atleast. I don't have sharepoint designer. My list is a list created using the create customlist feature in Sharepoint. How do you add the events and function to the fields?