Custom Javascript Onload Functions conflicting with Salesforce.com Onload Functions

Recently started using a little snippet of javascript code that takes the value previously entered value in a form field such as ‘Search’ and re-enters it on page submission. You would think this would be super easy in Apex/Visualforce but no. This is going to come up again shortly so stay tuned for a Apex/VF solution I’m sure in the coming weeks but until then here’s a cute little script I’m using that seems to consistently work:

<apex:form styleClass=”form-inline”>
<span class=”glyphicon glyphicon-search”/>&nbsp;&nbsp;&nbsp;&nbsp;
<apex:inputText html-placeholder=”Search Customers…” size=”40″ value=”{!searchStr2}” id=”search” styleClass=”form-control”/>
<script>
var Search = “{!$Component.Search}”;
</script>
<apex:commandButton value=”Search” action=”{!submit}” styleClass=”btn btn-primary”/>
</apex:form>

<!– Script to pre-populate the search URL –>
<script>
window.onload=function()
{
document.getElementById(Search).value = “{!$CurrentPage.parameters.srch}”;
};
</script>

This example shows off a pretty Bootstrap enabled search bar that I use on an internal site/application as part of a ‘menu’ include page.

Getting to the reason for the post, I recently added an additional page to do listview’s for a custom object. Immediately I noticed that with the above javascript the default listview functionality (Standarded and Enhanced) basically didn’t work. The only thing returned was the drop down, none of the buttons, tables, and links worked or even displayed. After doing some research found this page which has some insight on how to fix this:

Javascript Onload Handling

This is how you update the ‘script’ piece of the code snippet above:

<script>
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != ‘function’)
{
window.onload = func;
}
else
{
window.onload = function()
{
if (oldonload)
{
oldonload();
}
func();
}
}
}

addLoadEvent(function() {
/* more code to run on page load */
document.getElementById(Search).value = “{!$CurrentPage.parameters.srch}”;
});
</script>

Viola!~ Conflict resolved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *