Add functions and events to SharePoint form fields

April 4th, 2008 | Categories: SharePoint

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