Add functions and events to SharePoint form fields

April 4th, 2008 | Categories: SharePoint | Tags:

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.

Oznake ponudnika Technorati: ,
  1. Hal Angseesing
    April 4th, 2008 at 10:44
    Reply | Quote | #1

    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.

  2. Cliff
    April 24th, 2008 at 14:38
    Reply | Quote | #2

    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

  3. Boris Gomiunik
    April 24th, 2008 at 23:02
    Reply | Quote | #3

    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.

  4. gvijaikumar
    April 25th, 2008 at 07:47
    Reply | Quote | #4

    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

  5. Luca
    May 12th, 2008 at 13:02
    Reply | Quote | #5

    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

  6. karen
    May 28th, 2008 at 22:47
    Reply | Quote | #6

    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!

  7. Boris Gomiunik
    May 29th, 2008 at 20:31
    Reply | Quote | #7

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

  8. line47
    June 24th, 2008 at 22:27
    Reply | Quote | #8

    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?

  9. Anna
    July 4th, 2008 at 15:24
    Reply | Quote | #9

    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.

  10. Boris Gomiunik
    July 5th, 2008 at 10:40

    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.

  11. Anonymous
    August 20th, 2008 at 08:33

    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!

  12. John
    November 25th, 2008 at 02:54

    This works great for lists under 20 items, is there a way to use it for lists that have more than 20 items?

  13. Andrew
    November 25th, 2008 at 21:02

    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.

  14. ishay
    January 13th, 2009 at 10:38

    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 ?

  15. Sara
    May 30th, 2009 at 23:14

    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?

  16. May 31st, 2009 at 10:52

    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.

  17. vinay
    June 1st, 2009 at 06:13

    HI
    this can't be work on fields on new form?

  18. June 10th, 2009 at 00:40

    Where did all the previous comments go?

  19. Marcus
    June 26th, 2009 at 16:42

    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

  20. admin
    June 27th, 2009 at 15:57

    @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

  21. Marcus
    June 29th, 2009 at 15:21

    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.

  22. anonymous
    July 24th, 2009 at 00:30

    unable to fire the function on onchange()
    Please help

    • Boris Gomiunik
      August 4th, 2009 at 20:48

      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.

  23. Mike
    July 30th, 2009 at 22:39

    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

  24. Mike
    August 5th, 2009 at 18:48

    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?

  25. Boris Gomiunik
    August 6th, 2009 at 12:52

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

  26. Mike
    August 10th, 2009 at 23:27

    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

  27. Chris
    September 10th, 2009 at 15:49

    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

  28. Khushi
    October 20th, 2009 at 23:15

    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

  29. Boris Gomiunik
    October 26th, 2009 at 00:53

    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/

  30. Boris Gomiunik
    October 26th, 2009 at 01:01

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

  31. Brett
    January 11th, 2010 at 19:55

    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!

  32. Boris Gomiunik
    January 25th, 2010 at 09:51

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

  33. Sreedhar
    February 1st, 2010 at 14:35

    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

  34. Boris Gomiunik
    February 3rd, 2010 at 21:36

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

  35. January 13th, 2009 at 03:27

    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.

  36. Ishay
    January 14th, 2009 at 06:53

    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 .

  37. Sara
    June 1st, 2009 at 04:38

    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.

  38. Sara
    June 1st, 2009 at 20:10

    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?