Feb
24
2008

How to add a new event to controls in ListFormWebPart on the EditFrom.aspx / NewFrom.aspx pages

Background - The controls in EditForm.aspx and NewForm.aspx pages you see when you add/edit a item in SharePoint list library are generated by ListFormWebPart.

The problem - We want to attach a new event to the button (or any controls in this page). For example, we want to popup a javascript alert message when user click on "OK" button without breaking current onclick event.

Solution - This can be easily done by using javascript. And re-register onclick event for the OK button.

First, we need to find out the ID used by OK button control. When you view the source html of EditForm.aspx/NewForm.aspx, you can see the ID of OK button is ending with "SaveItem".

button_id

We also need to find out the default onclick event script of this OK button. So that we can insert our custom script at beginning of the default script or append it after.

button_onclick

From above screen shot we can see that default onclick event begins with string "If (PreSaveItem()).....". So we are going to replace this with our custom script. "alert('you have clicked OK');if (!PreSaveItem())"

The actual JavaScript like following: (The script can be warpped within <script> tag and put insided <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server"> in NewForm.aspx and EditForm.aspx )

 

_spBodyOnLoadFunctionNames.push("StartUpCustomScript");
function StartUpCustomScript() {    
    ChangeOkButtonOnclickEvent("Input","SaveItem");

function ChangeOkButtonOnclickEvent(tagName, identifier) {
    var len = identifier.length;
    var tags = document.getElementsByTagName(tagName);  /*find all Input type controls on page (ie. control with tag <Input/>)*/
    for (var i=0; i < tags.length; i++) {
        var tempString = tags[i].name;       
        if(tempString.indexOf(identifier) == tempString.length-len ) /*find any Input type controls on page has its name ending with 'SaveItem'*/
        {
           /*if found, replace it default onclick with our custom script*/
           var func = tags[i].attributes["onclick"].value.replace("if (!PreSaveItem())","alert('you have clicked OK');if (!PreSaveItem())");
           /*remove its default onclick event*/
           tags[i].onclick = null;
           /*re-register its onlick event with new script*/
           tags[i].attachEvent("onclick",new Function(func));
       }
    }
    return null;
}  

And now we click on OK button, we can see our Alert message :)

button_clicked

blog comments powered by Disqus